blob: 7a2519a9edd58b07e377e568bd44fefe5c066209 [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"
John McCall1cd76e82011-11-11 03:57:31 +000016#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000020#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/AST/StmtObjC.h"
John McCall209acbd2010-04-06 22:24:14 +000023#include "clang/AST/TypeLoc.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCall60d7b3a2010-08-24 06:29:42 +000038StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000039 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000040 if (!E) // FIXME: FullExprArg has no error state?
41 return StmtError();
42
Chris Lattner834a72a2008-07-25 23:18:17 +000043 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
44 // void expression for its side effects. Conversion to void allows any
45 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000046
Chris Lattner834a72a2008-07-25 23:18:17 +000047 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000048 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000049}
50
51
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000052StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000053 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Chris Lattner337e5502011-02-18 01:27:55 +000057StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner20401692009-04-12 20:13:14 +000061 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner24e1e702009-03-04 04:23:07 +000064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000065}
66
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000067void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000069
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000070 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000074 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000075 var->setUsed();
76
John McCall7acddac2011-06-17 06:42:21 +000077 // foreach variables are never actually initialized in the way that
78 // the parser came up with.
79 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000080
John McCall7acddac2011-06-17 06:42:21 +000081 // In ARC, we don't need to retain the iteration variable of a fast
82 // enumeration loop. Rather than actually trying to catch that
83 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000084 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000085 QualType type = var->getType();
86
87 // Only do this if we inferred the lifetime. Inferred lifetime
88 // will show up as a local qualifier because explicit lifetime
89 // should have shown up as an AttributedType instead.
90 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
91 // Add 'const' and mark the variable as pseudo-strong.
92 var->setType(type.withConst());
93 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000094 }
95 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000096}
97
Chandler Carruthec8058f2011-08-17 09:34:37 +000098/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +000099///
100/// Adding a cast to void (or other expression wrappers) will prevent the
101/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000102static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000103 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000104 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000105
106 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
107 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000108 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000109
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000113 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
114 if (Op->getOperator() != OO_EqualEqual &&
115 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000116 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000117
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121 } else {
122 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000123 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000124 }
125
126 // Suppress warnings when the operator, suspicious as it may be, comes from
127 // a macro expansion.
128 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000129 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000130
Chandler Carruthec8058f2011-08-17 09:34:37 +0000131 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132 << (unsigned)IsNotEqual << E->getSourceRange();
133
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000134 // If the LHS is a plausible entity to assign to, provide a fixit hint to
135 // correct common typos.
136 if (CanAssign) {
137 if (IsNotEqual)
138 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
139 << FixItHint::CreateReplacement(Loc, "|=");
140 else
141 S.Diag(Loc, diag::note_equality_comparison_to_assign)
142 << FixItHint::CreateReplacement(Loc, "=");
143 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000144
145 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000146}
147
Anders Carlsson636463e2009-07-30 22:17:18 +0000148void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
151
Anders Carlsson75443112009-07-30 22:39:03 +0000152 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000153 if (!E)
154 return;
155
Eli Friedmana6115062012-05-24 00:47:05 +0000156 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000157 SourceLocation Loc;
158 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000161 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner06b3a062012-08-31 22:39:21 +0000163 // If this is a GNU statement expression expanded from a macro, it is probably
164 // unused because it is a function-like macro that can be used as either an
165 // expression or statement. Don't warn, because it is almost certainly a
166 // false positive.
167 if (isa<StmtExpr>(E) && Loc.isMacroID())
168 return;
169
Chris Lattner419cfb32009-08-16 16:57:27 +0000170 // Okay, we have an unused result. Depending on what the base expression is,
171 // we might want to make a more specific diagnostic. Check for one of these
172 // cases now.
173 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000174 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000175 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000176 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
177 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000178
Chandler Carruthec8058f2011-08-17 09:34:37 +0000179 if (DiagnoseUnusedComparison(*this, E))
180 return;
181
Eli Friedmana6115062012-05-24 00:47:05 +0000182 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000183 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000184 if (E->getType()->isVoidType())
185 return;
186
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000187 // If the callee has attribute pure, const, or warn_unused_result, warn with
188 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000189 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000190 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000191 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000192 return;
193 }
194 if (FD->getAttr<PureAttr>()) {
195 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
196 return;
197 }
198 if (FD->getAttr<ConstAttr>()) {
199 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
200 return;
201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000202 }
John McCall12f78a62010-12-02 01:19:52 +0000203 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000204 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000205 Diag(Loc, diag::err_arc_unused_init_message) << R1;
206 return;
207 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000208 const ObjCMethodDecl *MD = ME->getMethodDecl();
209 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000210 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000211 return;
212 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000213 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
214 const Expr *Source = POE->getSyntacticForm();
215 if (isa<ObjCSubscriptRefExpr>(Source))
216 DiagID = diag::warn_unused_container_subscript_expr;
217 else
218 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000219 } else if (const CXXFunctionalCastExpr *FC
220 = dyn_cast<CXXFunctionalCastExpr>(E)) {
221 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
222 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
223 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000224 }
John McCall209acbd2010-04-06 22:24:14 +0000225 // Diagnose "(void*) blah" as a typo for "(void) blah".
226 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
227 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
228 QualType T = TI->getType();
229
230 // We really do want to use the non-canonical type here.
231 if (T == Context.VoidPtrTy) {
232 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
233
234 Diag(Loc, diag::warn_unused_voidptr)
235 << FixItHint::CreateRemoval(TL.getStarLoc());
236 return;
237 }
238 }
239
Eli Friedmana6115062012-05-24 00:47:05 +0000240 if (E->isGLValue() && E->getType().isVolatileQualified()) {
241 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
242 return;
243 }
244
Ted Kremenek351ba912011-02-23 01:52:04 +0000245 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000246}
247
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000248void Sema::ActOnStartOfCompoundStmt() {
249 PushCompoundScope();
250}
251
252void Sema::ActOnFinishOfCompoundStmt() {
253 PopCompoundScope();
254}
255
256sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
257 return getCurFunction()->CompoundScopes.back();
258}
259
John McCall60d7b3a2010-08-24 06:29:42 +0000260StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000261Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000262 MultiStmtArg elts, bool isStmtExpr) {
263 unsigned NumElts = elts.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +0000264 Stmt **Elts = elts.data();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000265 // If we're in C89 mode, check that we don't have any decls after stmts. If
266 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000267 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000268 // Note that __extension__ can be around a decl.
269 unsigned i = 0;
270 // Skip over all declarations.
271 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
272 /*empty*/;
273
274 // We found the end of the list or a statement. Scan for another declstmt.
275 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
276 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000278 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000279 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000280 Diag(D->getLocation(), diag::ext_mixed_decls_code);
281 }
282 }
Chris Lattner98414c12007-08-31 21:49:55 +0000283 // Warn about unused expressions in statements.
284 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000285 // Ignore statements that are last in a statement expression.
286 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000287 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Anders Carlsson636463e2009-07-30 22:17:18 +0000289 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000290 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000291
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000292 // Check for suspicious empty body (null statement) in `for' and `while'
293 // statements. Don't do anything for template instantiations, this just adds
294 // noise.
295 if (NumElts != 0 && !CurrentInstantiationScope &&
296 getCurCompoundScope().HasEmptyLoopBodies) {
297 for (unsigned i = 0; i != NumElts - 1; ++i)
298 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
299 }
300
Nico Weberd36aa352012-12-29 20:03:39 +0000301 return Owned(new (Context) CompoundStmt(Context,
302 llvm::makeArrayRef(Elts, NumElts),
303 L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000304}
305
John McCall60d7b3a2010-08-24 06:29:42 +0000306StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000307Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
308 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000309 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000310 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000311
John McCall781472f2010-08-25 08:40:02 +0000312 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000313 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000314 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000315 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
David Blaikie4e4d0842012-03-11 07:00:24 +0000317 if (!getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000318 // C99 6.8.4.2p3: The expression shall be an integer constant.
319 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000320 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
321 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
322 if (!LHSVal)
323 return StmtError();
324 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000325
326 // GCC extension: The expression shall be an integer constant.
327
Richard Smith282e7e62012-02-04 09:53:13 +0000328 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
329 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
330 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000331 }
332 }
333
Douglas Gregordbb26db2009-05-15 23:57:33 +0000334 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
335 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000336 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000337 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338}
339
Chris Lattner24e1e702009-03-04 04:23:07 +0000340/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000341void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000342 DiagnoseUnusedExprResult(SubStmt);
343
Chris Lattner24e1e702009-03-04 04:23:07 +0000344 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000345 CS->setSubStmt(SubStmt);
346}
347
John McCall60d7b3a2010-08-24 06:29:42 +0000348StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000349Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000350 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000351 DiagnoseUnusedExprResult(SubStmt);
352
John McCall781472f2010-08-25 08:40:02 +0000353 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000354 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000355 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000356 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000357
Douglas Gregordbb26db2009-05-15 23:57:33 +0000358 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000359 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000360 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000361}
362
John McCall60d7b3a2010-08-24 06:29:42 +0000363StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000364Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
365 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000366 // If the label was multiply defined, reject it now.
367 if (TheDecl->getStmt()) {
368 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
369 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000370 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 }
Sebastian Redlde307472009-01-11 00:38:46 +0000372
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000373 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000374 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
375 TheDecl->setStmt(LS);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000376 if (!TheDecl->isGnuLocal()) {
377 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000378 TheDecl->setLocation(IdentLoc);
Abramo Bagnaraac702782012-10-15 21:07:44 +0000379 }
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000380 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381}
382
Richard Smith534986f2012-04-14 00:33:13 +0000383StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000384 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000385 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000386 // Fill in the declaration and return it.
387 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000388 return Owned(LS);
389}
390
John McCall60d7b3a2010-08-24 06:29:42 +0000391StmtResult
John McCalld226f652010-08-21 09:40:31 +0000392Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000393 Stmt *thenStmt, SourceLocation ElseLoc,
394 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000395 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000397 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000398 if (CondVar) {
399 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000400 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000401 if (CondResult.isInvalid())
402 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000403 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000404 Expr *ConditionExpr = CondResult.takeAs<Expr>();
405 if (!ConditionExpr)
406 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407
Anders Carlsson75443112009-07-30 22:39:03 +0000408 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000409
John McCall9ae2f072010-08-23 23:25:46 +0000410 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000411 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
412 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000413 }
414
Anders Carlsson75443112009-07-30 22:39:03 +0000415 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000416
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000417 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000418 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000419}
420
Chris Lattnerf4021e72007-08-23 05:46:52 +0000421/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
422/// the specified width and sign. If an overflow occurs, detect it and emit
423/// the specified diagnostic.
424void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
425 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000426 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000427 unsigned DiagID) {
428 // Perform a conversion to the promoted condition type if needed.
429 if (NewWidth > Val.getBitWidth()) {
430 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000431 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000432 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000433
434 // If the input was signed and negative and the output is
435 // unsigned, don't bother to warn: this is implementation-defined
436 // behavior.
437 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000438 } else if (NewWidth < Val.getBitWidth()) {
439 // If this is a truncation, check for overflow.
440 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000441 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000442 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000443 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000444 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000445 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000446 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattnerf4021e72007-08-23 05:46:52 +0000448 // Regardless of whether a diagnostic was emitted, really do the
449 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000450 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000451 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000452 } else if (NewSign != Val.isSigned()) {
453 // Convert the sign to match the sign of the condition. This can cause
454 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000456 // behavior.
457 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000458 llvm::APSInt OldVal(Val);
459 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000460 }
461}
462
Chris Lattner0471f5b2007-08-23 18:29:20 +0000463namespace {
464 struct CaseCompareFunctor {
465 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
466 const llvm::APSInt &RHS) {
467 return LHS.first < RHS;
468 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000469 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
470 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
471 return LHS.first < RHS.first;
472 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000473 bool operator()(const llvm::APSInt &LHS,
474 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
475 return LHS < RHS.first;
476 }
477 };
478}
479
Chris Lattner764a7ce2007-09-21 18:15:22 +0000480/// CmpCaseVals - Comparison predicate for sorting case values.
481///
482static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
483 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
484 if (lhs.first < rhs.first)
485 return true;
486
487 if (lhs.first == rhs.first &&
488 lhs.second->getCaseLoc().getRawEncoding()
489 < rhs.second->getCaseLoc().getRawEncoding())
490 return true;
491 return false;
492}
493
Douglas Gregorba915af2010-02-08 22:24:16 +0000494/// CmpEnumVals - Comparison predicate for sorting enumeration values.
495///
496static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
497 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
498{
499 return lhs.first < rhs.first;
500}
501
502/// EqEnumVals - Comparison preficate for uniqing enumeration values.
503///
504static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
505 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
506{
507 return lhs.first == rhs.first;
508}
509
Chris Lattner5f048812009-10-16 16:45:22 +0000510/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
511/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000512static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
513 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
514 expr = cleanups->getSubExpr();
515 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
516 if (impcast->getCastKind() != CK_IntegralCast) break;
517 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000518 }
519 return expr->getType();
520}
521
John McCall60d7b3a2010-08-24 06:29:42 +0000522StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000523Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000524 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000525 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000526
Douglas Gregor586596f2010-05-06 17:25:47 +0000527 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000528 if (CondVar) {
529 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000530 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
531 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000532 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000533
John McCall9ae2f072010-08-23 23:25:46 +0000534 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000535 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536
John McCall9ae2f072010-08-23 23:25:46 +0000537 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000538 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregorab41fe92012-05-04 22:38:52 +0000540 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
541 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000542
Douglas Gregorab41fe92012-05-04 22:38:52 +0000543 public:
544 SwitchConvertDiagnoser(Expr *Cond)
545 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000546
Douglas Gregorab41fe92012-05-04 22:38:52 +0000547 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
548 QualType T) {
549 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
550 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000551
Douglas Gregorab41fe92012-05-04 22:38:52 +0000552 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
553 QualType T) {
554 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
555 << T << Cond->getSourceRange();
556 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000557
Douglas Gregorab41fe92012-05-04 22:38:52 +0000558 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
559 QualType T,
560 QualType ConvTy) {
561 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
562 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000563
Douglas Gregorab41fe92012-05-04 22:38:52 +0000564 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
565 QualType ConvTy) {
566 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
567 << ConvTy->isEnumeralType() << ConvTy;
568 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000569
Douglas Gregorab41fe92012-05-04 22:38:52 +0000570 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
571 QualType T) {
572 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
573 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000574
Douglas Gregorab41fe92012-05-04 22:38:52 +0000575 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
576 QualType ConvTy) {
577 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
578 << ConvTy->isEnumeralType() << ConvTy;
579 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000580
Douglas Gregorab41fe92012-05-04 22:38:52 +0000581 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
582 QualType T,
583 QualType ConvTy) {
584 return DiagnosticBuilder::getEmpty();
585 }
586 } SwitchDiagnoser(Cond);
587
John McCall9ae2f072010-08-23 23:25:46 +0000588 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000589 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000590 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000591 if (CondResult.isInvalid()) return StmtError();
592 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
John McCalla8e0cd82011-08-06 07:30:58 +0000594 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
595 CondResult = UsualUnaryConversions(Cond);
596 if (CondResult.isInvalid()) return StmtError();
597 Cond = CondResult.take();
598
John McCalld226f652010-08-21 09:40:31 +0000599 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000600 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000601 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000602 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000603 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000604 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000605 }
John McCallb60a77e2010-08-01 00:26:45 +0000606
John McCall781472f2010-08-25 08:40:02 +0000607 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608
John McCall9ae2f072010-08-23 23:25:46 +0000609 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000610 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000611 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000612}
613
Gabor Greif28164ab2010-10-01 22:05:14 +0000614static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
615 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000616 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000617 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000618 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000619 Val.setIsSigned(IsSigned);
620}
621
John McCall60d7b3a2010-08-24 06:29:42 +0000622StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000623Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
624 Stmt *BodyStmt) {
625 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000626 assert(SS == getCurFunction()->SwitchStack.back() &&
627 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000628
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000629 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000630 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000631
Chris Lattnerf4021e72007-08-23 05:46:52 +0000632 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000633 if (!CondExpr) return StmtError();
634
635 QualType CondType = CondExpr->getType();
636
John McCall0fb97082010-05-18 03:19:21 +0000637 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000638 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000639 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000640
Chris Lattner5f048812009-10-16 16:45:22 +0000641 // C++ 6.4.2.p2:
642 // Integral promotions are performed (on the switch condition).
643 //
644 // A case value unrepresentable by the original switch condition
645 // type (before the promotion) doesn't make sense, even when it can
646 // be represented by the promoted type. Therefore we need to find
647 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000648 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000649 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000650 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000651 // appropriate type now, just return an error.
652 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000653 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000654
Chris Lattner2b334bb2010-04-16 23:34:13 +0000655 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000656 // switch(bool_expr) {...} is often a programmer error, e.g.
657 // switch(n && mask) { ... } // Doh - should be "n & mask".
658 // One can always use an if statement instead of switch(bool_expr).
659 Diag(SwitchLoc, diag::warn_bool_switch_condition)
660 << CondExpr->getSourceRange();
661 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000662 }
Sebastian Redlde307472009-01-11 00:38:46 +0000663
Chris Lattnerf4021e72007-08-23 05:46:52 +0000664 // Get the bitwidth of the switched-on value before promotions. We must
665 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000666 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000667 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000668 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000669 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier1093f492012-08-10 17:56:09 +0000670 bool CondIsSigned
Douglas Gregor575a1c92011-05-20 16:38:50 +0000671 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerf4021e72007-08-23 05:46:52 +0000673 // Accumulate all of the case values in a vector so that we can sort them
674 // and detect duplicates. This vector contains the APInt for the case after
675 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000676 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000677 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattnerf4021e72007-08-23 05:46:52 +0000679 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000680 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
681 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattnerf4021e72007-08-23 05:46:52 +0000683 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000685 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Douglas Gregordbb26db2009-05-15 23:57:33 +0000687 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000688 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000690 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000691 if (TheDefaultStmt) {
692 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000693 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000694
Chris Lattnerf4021e72007-08-23 05:46:52 +0000695 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000696 // we'll return a valid AST. This requires recursing down the AST and
697 // finding it, not something we are set up to do right now. For now,
698 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000699 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000700 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000701 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerf4021e72007-08-23 05:46:52 +0000703 } else {
704 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner1e0a3902008-01-16 19:17:22 +0000706 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000707
708 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
709 HasDependentValue = true;
710 break;
711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Richard Smith8ef7b202012-01-18 23:55:52 +0000713 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
David Blaikie4e4d0842012-03-11 07:00:24 +0000715 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000716 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
717 // constant expression of the promoted type of the switch condition.
718 ExprResult ConvLo =
719 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
720 if (ConvLo.isInvalid()) {
721 CaseListIsErroneous = true;
722 continue;
723 }
724 Lo = ConvLo.take();
725 } else {
726 // We already verified that the expression has a i-c-e value (C99
727 // 6.8.4.2p3) - get that value now.
728 LoVal = Lo->EvaluateKnownConstInt(Context);
729
730 // If the LHS is not the same type as the condition, insert an implicit
731 // cast.
732 Lo = DefaultLvalueConversion(Lo).take();
733 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
734 }
735
736 // Convert the value to the same width/sign as the condition had prior to
737 // integral promotions.
738 //
739 // FIXME: This causes us to reject valid code:
740 // switch ((char)c) { case 256: case 0: return 0; }
741 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000742 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000743 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000744 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000745
Chris Lattner1e0a3902008-01-16 19:17:22 +0000746 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000748 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000749 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000750 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000751 CS->getRHS()->isValueDependent()) {
752 HasDependentValue = true;
753 break;
754 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000755 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000756 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000757 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000758 }
759 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000760
761 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000762 // If we don't have a default statement, check whether the
763 // condition is constant.
764 llvm::APSInt ConstantCondValue;
765 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000766 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000767 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000768 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
769 Expr::SE_AllowSideEffects);
770 assert(!HasConstantCond ||
771 (ConstantCondValue.getBitWidth() == CondWidth &&
772 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000773 }
Richard Smith80d4b552011-12-28 19:48:30 +0000774 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000775
Douglas Gregordbb26db2009-05-15 23:57:33 +0000776 // Sort all the scalar case values so we can easily detect duplicates.
777 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
778
779 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000780 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
781 if (ShouldCheckConstantCond &&
782 CaseVals[i].first == ConstantCondValue)
783 ShouldCheckConstantCond = false;
784
785 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000786 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000787 // First, determine if either case value has a name
788 StringRef PrevString, CurrString;
789 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
790 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
791 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
792 PrevString = DeclRef->getDecl()->getName();
793 }
794 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
795 CurrString = DeclRef->getDecl()->getName();
796 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000797 llvm::SmallString<16> CaseValStr;
798 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000799
800 if (PrevString == CurrString)
801 Diag(CaseVals[i].second->getLHS()->getLocStart(),
802 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000803 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000804 else
805 Diag(CaseVals[i].second->getLHS()->getLocStart(),
806 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000807 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
808 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000809 CaseValStr;
810
John McCall0fb97082010-05-18 03:19:21 +0000811 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000812 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000813 // FIXME: We really want to remove the bogus case stmt from the
814 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000815 CaseListIsErroneous = true;
816 }
817 }
818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Douglas Gregordbb26db2009-05-15 23:57:33 +0000820 // Detect duplicate case ranges, which usually don't exist at all in
821 // the first place.
822 if (!CaseRanges.empty()) {
823 // Sort all the case ranges by their low value so we can easily detect
824 // overlaps between ranges.
825 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Douglas Gregordbb26db2009-05-15 23:57:33 +0000827 // Scan the ranges, computing the high values and removing empty ranges.
828 std::vector<llvm::APSInt> HiVals;
829 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000830 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000831 CaseStmt *CR = CaseRanges[i].second;
832 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000833 llvm::APSInt HiVal;
834
David Blaikie4e4d0842012-03-11 07:00:24 +0000835 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000836 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
837 // constant expression of the promoted type of the switch condition.
838 ExprResult ConvHi =
839 CheckConvertedConstantExpression(Hi, CondType, HiVal,
840 CCEK_CaseValue);
841 if (ConvHi.isInvalid()) {
842 CaseListIsErroneous = true;
843 continue;
844 }
845 Hi = ConvHi.take();
846 } else {
847 HiVal = Hi->EvaluateKnownConstInt(Context);
848
849 // If the RHS is not the same type as the condition, insert an
850 // implicit cast.
851 Hi = DefaultLvalueConversion(Hi).take();
852 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Douglas Gregordbb26db2009-05-15 23:57:33 +0000855 // Convert the value to the same width/sign as the condition.
856 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000857 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000858 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregordbb26db2009-05-15 23:57:33 +0000860 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Douglas Gregordbb26db2009-05-15 23:57:33 +0000862 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000863 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000864 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
865 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000866 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000867 CaseRanges.erase(CaseRanges.begin()+i);
868 --i, --e;
869 continue;
870 }
John McCall0fb97082010-05-18 03:19:21 +0000871
872 if (ShouldCheckConstantCond &&
873 LoVal <= ConstantCondValue &&
874 ConstantCondValue <= HiVal)
875 ShouldCheckConstantCond = false;
876
Douglas Gregordbb26db2009-05-15 23:57:33 +0000877 HiVals.push_back(HiVal);
878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregordbb26db2009-05-15 23:57:33 +0000880 // Rescan the ranges, looking for overlap with singleton values and other
881 // ranges. Since the range list is sorted, we only need to compare case
882 // ranges with their neighbors.
883 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
884 llvm::APSInt &CRLo = CaseRanges[i].first;
885 llvm::APSInt &CRHi = HiVals[i];
886 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregordbb26db2009-05-15 23:57:33 +0000888 // Check to see whether the case range overlaps with any
889 // singleton cases.
890 CaseStmt *OverlapStmt = 0;
891 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregordbb26db2009-05-15 23:57:33 +0000893 // Find the smallest value >= the lower bound. If I is in the
894 // case range, then we have overlap.
895 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
896 CaseVals.end(), CRLo,
897 CaseCompareFunctor());
898 if (I != CaseVals.end() && I->first < CRHi) {
899 OverlapVal = I->first; // Found overlap with scalar.
900 OverlapStmt = I->second;
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Douglas Gregordbb26db2009-05-15 23:57:33 +0000903 // Find the smallest value bigger than the upper bound.
904 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
905 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
906 OverlapVal = (I-1)->first; // Found overlap with scalar.
907 OverlapStmt = (I-1)->second;
908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Douglas Gregordbb26db2009-05-15 23:57:33 +0000910 // Check to see if this case stmt overlaps with the subsequent
911 // case range.
912 if (i && CRLo <= HiVals[i-1]) {
913 OverlapVal = HiVals[i-1]; // Found overlap with range.
914 OverlapStmt = CaseRanges[i-1].second;
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregordbb26db2009-05-15 23:57:33 +0000917 if (OverlapStmt) {
918 // If we have a duplicate, report it.
919 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
920 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000921 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000922 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000923 // FIXME: We really want to remove the bogus case stmt from the
924 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000925 CaseListIsErroneous = true;
926 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000927 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000928 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000929
John McCall0fb97082010-05-18 03:19:21 +0000930 // Complain if we have a constant condition and we didn't find a match.
931 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
932 // TODO: it would be nice if we printed enums as enums, chars as
933 // chars, etc.
934 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
935 << ConstantCondValue.toString(10)
936 << CondExpr->getSourceRange();
937 }
938
939 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000940 // values. We only issue a warning if there is not 'default:', but
941 // we still do the analysis to preserve this information in the AST
942 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000943 //
Chris Lattnerce784612010-09-16 17:09:42 +0000944 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000945
Douglas Gregorba915af2010-02-08 22:24:16 +0000946 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000947 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000948 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000949 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000950 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000951 EnumValsTy EnumVals;
952
John McCall0fb97082010-05-18 03:19:21 +0000953 // Gather all enum values, set their type and sort them,
954 // allowing easier comparison with CaseVals.
955 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000956 EDI != ED->enumerator_end(); ++EDI) {
957 llvm::APSInt Val = EDI->getInitVal();
958 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000959 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000960 }
961 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000962 EnumValsTy::iterator EIend =
963 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000964
965 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000966 EnumValsTy::const_iterator EI = EnumVals.begin();
967 for (CaseValsTy::const_iterator CI = CaseVals.begin();
968 CI != CaseVals.end(); CI++) {
969 while (EI != EIend && EI->first < CI->first)
970 EI++;
971 if (EI == EIend || EI->first > CI->first)
972 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000973 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000974 }
975 // See which of case ranges aren't in enum
976 EI = EnumVals.begin();
977 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
978 RI != CaseRanges.end() && EI != EIend; RI++) {
979 while (EI != EIend && EI->first < RI->first)
980 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
David Blaikie93667502012-01-22 02:31:55 +0000982 if (EI == EIend || EI->first != RI->first) {
983 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000984 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000985 }
David Blaikie93667502012-01-22 02:31:55 +0000986
Chad Rosier1093f492012-08-10 17:56:09 +0000987 llvm::APSInt Hi =
David Blaikie93667502012-01-22 02:31:55 +0000988 RI->second->getRHS()->EvaluateKnownConstInt(Context);
989 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
990 while (EI != EIend && EI->first < Hi)
991 EI++;
992 if (EI == EIend || EI->first != Hi)
993 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000994 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +0000995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Ted Kremenek559fb552010-09-09 00:05:53 +0000997 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000998 CaseValsTy::const_iterator CI = CaseVals.begin();
999 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +00001000 bool hasCasesNotInSwitch = false;
1001
Chris Lattner5f9e2722011-07-23 10:55:15 +00001002 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001003
David Blaikie93667502012-01-22 02:31:55 +00001004 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +00001005 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +00001006 llvm::APSInt CIVal;
1007 while (CI != CaseVals.end() && CI->first < EI->first)
1008 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001009
Douglas Gregorba915af2010-02-08 22:24:16 +00001010 if (CI != CaseVals.end() && CI->first == EI->first)
1011 continue;
1012
Ted Kremenek559fb552010-09-09 00:05:53 +00001013 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001014 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001015 llvm::APSInt Hi =
1016 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001017 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001018 if (EI->first <= Hi)
1019 break;
1020 }
1021
Ted Kremenek559fb552010-09-09 00:05:53 +00001022 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001023 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001024 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001025 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001026 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001027
David Blaikie585d7792012-01-23 04:46:12 +00001028 if (TheDefaultStmt && UnhandledNames.empty())
1029 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001030
Chris Lattnerce784612010-09-16 17:09:42 +00001031 // Produce a nice diagnostic if multiple values aren't handled.
1032 switch (UnhandledNames.size()) {
1033 case 0: break;
1034 case 1:
Chad Rosier1093f492012-08-10 17:56:09 +00001035 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001036 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001037 << UnhandledNames[0];
1038 break;
1039 case 2:
Chad Rosier1093f492012-08-10 17:56:09 +00001040 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie585d7792012-01-23 04:46:12 +00001041 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001042 << UnhandledNames[0] << UnhandledNames[1];
1043 break;
1044 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001045 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1046 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001047 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1048 break;
1049 default:
David Blaikie585d7792012-01-23 04:46:12 +00001050 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1051 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001052 << (unsigned)UnhandledNames.size()
1053 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1054 break;
1055 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001056
1057 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001058 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001059 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001060 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001061
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001062 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1063 diag::warn_empty_switch_body);
1064
Mike Stump390b4cc2009-05-16 07:39:55 +00001065 // FIXME: If the case list was broken is some way, we don't have a good system
1066 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001067 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001068 return StmtError();
1069
Sebastian Redlde307472009-01-11 00:38:46 +00001070 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001071}
1072
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001073void
1074Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1075 Expr *SrcExpr) {
1076 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier1093f492012-08-10 17:56:09 +00001077 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001078 == DiagnosticsEngine::Ignored)
1079 return;
Chad Rosier1093f492012-08-10 17:56:09 +00001080
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001081 if (const EnumType *ET = DstType->getAs<EnumType>())
1082 if (!Context.hasSameType(SrcType, DstType) &&
1083 SrcType->isIntegerType()) {
1084 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1085 SrcExpr->isIntegerConstantExpr(Context)) {
1086 // Get the bitwidth of the enum value before promotions.
1087 unsigned DstWith = Context.getIntWidth(DstType);
1088 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1089
1090 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1091 const EnumDecl *ED = ET->getDecl();
1092 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1093 EnumValsTy;
1094 EnumValsTy EnumVals;
Chad Rosier1093f492012-08-10 17:56:09 +00001095
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001096 // Gather all enum values, set their type and sort them,
1097 // allowing easier comparison with rhs constant.
1098 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1099 EDI != ED->enumerator_end(); ++EDI) {
1100 llvm::APSInt Val = EDI->getInitVal();
1101 AdjustAPSInt(Val, DstWith, DstIsSigned);
1102 EnumVals.push_back(std::make_pair(Val, *EDI));
1103 }
1104 if (EnumVals.empty())
1105 return;
1106 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1107 EnumValsTy::iterator EIend =
1108 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier1093f492012-08-10 17:56:09 +00001109
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001110 // See which case values aren't in enum.
1111 EnumValsTy::const_iterator EI = EnumVals.begin();
1112 while (EI != EIend && EI->first < RhsVal)
1113 EI++;
1114 if (EI == EIend || EI->first != RhsVal) {
1115 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1116 << DstType;
1117 }
1118 }
1119 }
1120}
1121
John McCall60d7b3a2010-08-24 06:29:42 +00001122StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001123Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001124 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001125 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126
Douglas Gregor5656e142009-11-24 21:15:44 +00001127 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001128 if (CondVar) {
1129 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001130 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001131 if (CondResult.isInvalid())
1132 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001133 }
John McCall9ae2f072010-08-23 23:25:46 +00001134 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001135 if (!ConditionExpr)
1136 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001137
John McCall9ae2f072010-08-23 23:25:46 +00001138 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001140 if (isa<NullStmt>(Body))
1141 getCurCompoundScope().setHasEmptyLoopBodies();
1142
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001143 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001144 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001145}
1146
John McCall60d7b3a2010-08-24 06:29:42 +00001147StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001148Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001149 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001150 Expr *Cond, SourceLocation CondRParen) {
1151 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001152
John Wiegley429bb272011-04-08 18:41:53 +00001153 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenko898a7a22012-11-18 22:28:42 +00001154 if (CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001155 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001156 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001157
John McCallb4eb64d2010-10-08 02:01:28 +00001158 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001159 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001160 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001161 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001162 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001163
John McCall9ae2f072010-08-23 23:25:46 +00001164 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001165
John McCall9ae2f072010-08-23 23:25:46 +00001166 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001167}
1168
Richard Trieu694e7962012-04-30 18:01:30 +00001169namespace {
1170 // This visitor will traverse a conditional statement and store all
1171 // the evaluated decls into a vector. Simple is set to true if none
1172 // of the excluded constructs are used.
1173 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1174 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1175 llvm::SmallVector<SourceRange, 10> &Ranges;
1176 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001177public:
1178 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1179
1180 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001181 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001182 Inherited(S.Context),
1183 Decls(Decls),
1184 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001185 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001186
1187 bool isSimple() { return Simple; }
1188
1189 // Replaces the method in EvaluatedExprVisitor.
1190 void VisitMemberExpr(MemberExpr* E) {
1191 Simple = false;
1192 }
1193
1194 // Any Stmt not whitelisted will cause the condition to be marked complex.
1195 void VisitStmt(Stmt *S) {
1196 Simple = false;
1197 }
1198
1199 void VisitBinaryOperator(BinaryOperator *E) {
1200 Visit(E->getLHS());
1201 Visit(E->getRHS());
1202 }
1203
1204 void VisitCastExpr(CastExpr *E) {
1205 Visit(E->getSubExpr());
1206 }
1207
1208 void VisitUnaryOperator(UnaryOperator *E) {
1209 // Skip checking conditionals with derefernces.
1210 if (E->getOpcode() == UO_Deref)
1211 Simple = false;
1212 else
1213 Visit(E->getSubExpr());
1214 }
1215
1216 void VisitConditionalOperator(ConditionalOperator *E) {
1217 Visit(E->getCond());
1218 Visit(E->getTrueExpr());
1219 Visit(E->getFalseExpr());
1220 }
1221
1222 void VisitParenExpr(ParenExpr *E) {
1223 Visit(E->getSubExpr());
1224 }
1225
1226 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1227 Visit(E->getOpaqueValue()->getSourceExpr());
1228 Visit(E->getFalseExpr());
1229 }
1230
1231 void VisitIntegerLiteral(IntegerLiteral *E) { }
1232 void VisitFloatingLiteral(FloatingLiteral *E) { }
1233 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1234 void VisitCharacterLiteral(CharacterLiteral *E) { }
1235 void VisitGNUNullExpr(GNUNullExpr *E) { }
1236 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1237
1238 void VisitDeclRefExpr(DeclRefExpr *E) {
1239 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1240 if (!VD) return;
1241
1242 Ranges.push_back(E->getSourceRange());
1243
1244 Decls.insert(VD);
1245 }
1246
1247 }; // end class DeclExtractor
1248
1249 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier1093f492012-08-10 17:56:09 +00001250 // context.
Richard Trieu694e7962012-04-30 18:01:30 +00001251 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1252 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1253 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001254
1255public:
1256 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1257
1258 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1259 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1260 if (!Statement) return;
1261
1262 Visit(Statement);
1263 }
1264
1265 void VisitReturnStmt(ReturnStmt *S) {
1266 FoundDecl = true;
1267 }
1268
1269 void VisitBreakStmt(BreakStmt *S) {
1270 FoundDecl = true;
1271 }
1272
1273 void VisitGotoStmt(GotoStmt *S) {
1274 FoundDecl = true;
1275 }
1276
1277 void VisitCastExpr(CastExpr *E) {
1278 if (E->getCastKind() == CK_LValueToRValue)
1279 CheckLValueToRValueCast(E->getSubExpr());
1280 else
1281 Visit(E->getSubExpr());
1282 }
1283
1284 void CheckLValueToRValueCast(Expr *E) {
1285 E = E->IgnoreParenImpCasts();
1286
1287 if (isa<DeclRefExpr>(E)) {
1288 return;
1289 }
1290
1291 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1292 Visit(CO->getCond());
1293 CheckLValueToRValueCast(CO->getTrueExpr());
1294 CheckLValueToRValueCast(CO->getFalseExpr());
1295 return;
1296 }
1297
1298 if (BinaryConditionalOperator *BCO =
1299 dyn_cast<BinaryConditionalOperator>(E)) {
1300 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1301 CheckLValueToRValueCast(BCO->getFalseExpr());
1302 return;
1303 }
1304
1305 Visit(E);
1306 }
1307
1308 void VisitDeclRefExpr(DeclRefExpr *E) {
1309 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1310 if (Decls.count(VD))
1311 FoundDecl = true;
1312 }
1313
1314 bool FoundDeclInUse() { return FoundDecl; }
1315
1316 }; // end class DeclMatcher
1317
1318 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1319 Expr *Third, Stmt *Body) {
1320 // Condition is empty
1321 if (!Second) return;
1322
1323 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1324 Second->getLocStart())
1325 == DiagnosticsEngine::Ignored)
1326 return;
1327
1328 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1329 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1330 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001331 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001332 DE.Visit(Second);
1333
1334 // Don't analyze complex conditionals.
1335 if (!DE.isSimple()) return;
1336
1337 // No decls found.
1338 if (Decls.size() == 0) return;
1339
Richard Trieu90875992012-05-04 03:01:54 +00001340 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001341 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1342 E = Decls.end();
1343 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001344 if ((*I)->getType().isVolatileQualified() ||
1345 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001346
1347 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1348 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1349 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1350 return;
1351
1352 // Load decl names into diagnostic.
1353 if (Decls.size() > 4)
1354 PDiag << 0;
1355 else {
1356 PDiag << Decls.size();
1357 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1358 E = Decls.end();
1359 I != E; ++I)
1360 PDiag << (*I)->getDeclName();
1361 }
1362
1363 // Load SourceRanges into diagnostic if there is room.
1364 // Otherwise, load the SourceRange of the conditional expression.
1365 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1366 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1367 E = Ranges.end();
1368 I != E; ++I)
1369 PDiag << *I;
1370 else
1371 PDiag << Second->getSourceRange();
1372
1373 S.Diag(Ranges.begin()->getBegin(), PDiag);
1374 }
1375
1376} // end namespace
1377
John McCall60d7b3a2010-08-24 06:29:42 +00001378StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001379Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001380 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001381 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001382 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001383 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001384 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001385 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1386 // declare identifiers for objects having storage class 'auto' or
1387 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001388 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1389 DI!=DE; ++DI) {
1390 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001391 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001392 VD = 0;
1393 if (VD == 0)
1394 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1395 // FIXME: mark decl erroneous!
1396 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001397 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001399
Richard Trieu694e7962012-04-30 18:01:30 +00001400 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1401
John McCall60d7b3a2010-08-24 06:29:42 +00001402 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001403 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001404 if (secondVar) {
1405 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001406 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001407 if (SecondResult.isInvalid())
1408 return StmtError();
1409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001411 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412
Anders Carlsson3af708f2009-08-01 01:39:59 +00001413 DiagnoseUnusedExprResult(First);
1414 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001415 DiagnoseUnusedExprResult(Body);
1416
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001417 if (isa<NullStmt>(Body))
1418 getCurCompoundScope().setHasEmptyLoopBodies();
1419
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001420 return Owned(new (Context) ForStmt(Context, First,
1421 SecondResult.take(), ConditionVar,
1422 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001423 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001424}
1425
John McCallf6a16482010-12-04 03:47:34 +00001426/// In an Objective C collection iteration statement:
1427/// for (x in y)
1428/// x can be an arbitrary l-value expression. Bind it up as a
1429/// full-expression.
1430StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001431 // Reduce placeholder expressions here. Note that this rejects the
1432 // use of pseudo-object l-values in this position.
1433 ExprResult result = CheckPlaceholderExpr(E);
1434 if (result.isInvalid()) return StmtError();
1435 E = result.take();
1436
John McCallf6a16482010-12-04 03:47:34 +00001437 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001438
1439 result = MaybeCreateExprWithCleanups(E);
1440 if (result.isInvalid()) return StmtError();
1441
1442 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001443}
1444
John McCall990567c2011-07-27 01:07:15 +00001445ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001446Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1447 if (!collection)
1448 return ExprError();
Chad Rosier1093f492012-08-10 17:56:09 +00001449
John McCall990567c2011-07-27 01:07:15 +00001450 // Bail out early if we've got a type-dependent expression.
1451 if (collection->isTypeDependent()) return Owned(collection);
1452
1453 // Perform normal l-value conversion.
1454 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1455 if (result.isInvalid())
1456 return ExprError();
1457 collection = result.take();
1458
1459 // The operand needs to have object-pointer type.
1460 // TODO: should we do a contextual conversion?
1461 const ObjCObjectPointerType *pointerType =
1462 collection->getType()->getAs<ObjCObjectPointerType>();
1463 if (!pointerType)
1464 return Diag(forLoc, diag::err_collection_expr_type)
1465 << collection->getType() << collection->getSourceRange();
1466
1467 // Check that the operand provides
1468 // - countByEnumeratingWithState:objects:count:
1469 const ObjCObjectType *objectType = pointerType->getObjectType();
1470 ObjCInterfaceDecl *iface = objectType->getInterface();
1471
1472 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001473 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier1093f492012-08-10 17:56:09 +00001474 if (iface &&
Douglas Gregorb3029962011-11-14 22:10:01 +00001475 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001476 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001477 ? diag::err_arc_collection_forward
1478 : 0,
1479 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001480 // Otherwise, if we have any useful type information, check that
1481 // the type declares the appropriate method.
1482 } else if (iface || !objectType->qual_empty()) {
1483 IdentifierInfo *selectorIdents[] = {
1484 &Context.Idents.get("countByEnumeratingWithState"),
1485 &Context.Idents.get("objects"),
1486 &Context.Idents.get("count")
1487 };
1488 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1489
1490 ObjCMethodDecl *method = 0;
1491
1492 // If there's an interface, look in both the public and private APIs.
1493 if (iface) {
1494 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001495 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001496 }
1497
1498 // Also check protocol qualifiers.
1499 if (!method)
1500 method = LookupMethodInQualifiedType(selector, pointerType,
1501 /*instance*/ true);
1502
1503 // If we didn't find it anywhere, give up.
1504 if (!method) {
1505 Diag(forLoc, diag::warn_collection_expr_type)
1506 << collection->getType() << selector << collection->getSourceRange();
1507 }
1508
1509 // TODO: check for an incompatible signature?
1510 }
1511
1512 // Wrap up any cleanups in the expression.
1513 return Owned(MaybeCreateExprWithCleanups(collection));
1514}
1515
John McCall60d7b3a2010-08-24 06:29:42 +00001516StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001517Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001518 Stmt *First, Expr *collection,
1519 SourceLocation RParenLoc) {
Chad Rosier1093f492012-08-10 17:56:09 +00001520
1521 ExprResult CollectionExprResult =
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001522 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier1093f492012-08-10 17:56:09 +00001523
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001524 if (First) {
1525 QualType FirstType;
1526 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001527 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001528 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1529 diag::err_toomany_element_decls));
1530
John McCallf85e1932011-06-15 23:02:42 +00001531 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1532 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001533 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1534 // declare identifiers for objects having storage class 'auto' or
1535 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001536 if (!D->hasLocalStorage())
1537 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001538 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001539 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001540 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001541 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001542 return StmtError(Diag(First->getLocStart(),
1543 diag::err_selector_element_not_lvalue)
1544 << First->getSourceRange());
1545
Mike Stump1eb44332009-09-09 15:08:12 +00001546 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001547 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001548 if (!FirstType->isDependentType() &&
1549 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001550 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001551 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1552 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001553 }
Chad Rosier1093f492012-08-10 17:56:09 +00001554
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001555 if (CollectionExprResult.isInvalid())
1556 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001557
1558 return Owned(new (Context) ObjCForCollectionStmt(First,
1559 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001560 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001561}
Reid Spencer5f016e22007-07-11 17:01:13 +00001562
Richard Smithad762fc2011-04-14 22:09:26 +00001563/// Finish building a variable declaration for a for-range statement.
1564/// \return true if an error occurs.
1565static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1566 SourceLocation Loc, int diag) {
1567 // Deduce the type for the iterator variable now rather than leaving it to
1568 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1569 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001570 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001571 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1572 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001573 SemaRef.Diag(Loc, diag) << Init->getType();
1574 if (!InitTSI) {
1575 Decl->setInvalidDecl();
1576 return true;
1577 }
1578 Decl->setTypeSourceInfo(InitTSI);
1579 Decl->setType(InitTSI->getType());
1580
John McCallf85e1932011-06-15 23:02:42 +00001581 // In ARC, infer lifetime.
1582 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1583 // we're doing the equivalent of fast iteration.
Chad Rosier1093f492012-08-10 17:56:09 +00001584 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001585 SemaRef.inferObjCARCLifetime(Decl))
1586 Decl->setInvalidDecl();
1587
Richard Smithad762fc2011-04-14 22:09:26 +00001588 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1589 /*TypeMayContainAuto=*/false);
1590 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001591 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001592 return false;
1593}
1594
Sam Panzere1715b62012-08-21 00:52:01 +00001595namespace {
1596
Richard Smithad762fc2011-04-14 22:09:26 +00001597/// Produce a note indicating which begin/end function was implicitly called
Sam Panzere1715b62012-08-21 00:52:01 +00001598/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smithad762fc2011-04-14 22:09:26 +00001599/// nor from the diagnostics produced when analysing the implicit expressions
1600/// required in a for-range statement.
1601void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzere1715b62012-08-21 00:52:01 +00001602 Sema::BeginEndFunction BEF) {
Richard Smithad762fc2011-04-14 22:09:26 +00001603 CallExpr *CE = dyn_cast<CallExpr>(E);
1604 if (!CE)
1605 return;
1606 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1607 if (!D)
1608 return;
1609 SourceLocation Loc = D->getLocation();
1610
1611 std::string Description;
1612 bool IsTemplate = false;
1613 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1614 Description = SemaRef.getTemplateArgumentBindingsText(
1615 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1616 IsTemplate = true;
1617 }
1618
1619 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1620 << BEF << IsTemplate << Description << E->getType();
1621}
1622
Sam Panzere1715b62012-08-21 00:52:01 +00001623/// Build a variable declaration for a for-range statement.
1624VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1625 QualType Type, const char *Name) {
1626 DeclContext *DC = SemaRef.CurContext;
1627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1629 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1630 TInfo, SC_Auto, SC_None);
1631 Decl->setImplicit();
1632 return Decl;
Richard Smithad762fc2011-04-14 22:09:26 +00001633}
1634
1635}
1636
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001637static bool ObjCEnumerationCollection(Expr *Collection) {
1638 return !Collection->isTypeDependent()
1639 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1640}
1641
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001642/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001643///
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001644/// C++11 [stmt.ranged]:
Richard Smithad762fc2011-04-14 22:09:26 +00001645/// A range-based for statement is equivalent to
1646///
1647/// {
1648/// auto && __range = range-init;
1649/// for ( auto __begin = begin-expr,
1650/// __end = end-expr;
1651/// __begin != __end;
1652/// ++__begin ) {
1653/// for-range-declaration = *__begin;
1654/// statement
1655/// }
1656/// }
1657///
1658/// The body of the loop is not available yet, since it cannot be analysed until
1659/// we have determined the type of the for-range-declaration.
1660StmtResult
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001661Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001662 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smith8b533d92012-09-20 21:52:32 +00001663 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001664 if (!First || !Range)
1665 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00001666
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001667 if (ObjCEnumerationCollection(Range))
Sam Panzerbc20bbb2012-08-16 21:47:25 +00001668 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001669
1670 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1671 assert(DS && "first part of for range not a decl stmt");
1672
1673 if (!DS->isSingleDecl()) {
1674 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1675 return StmtError();
1676 }
1677 if (DS->getSingleDecl()->isInvalidDecl())
1678 return StmtError();
1679
1680 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1681 return StmtError();
1682
1683 // Build auto && __range = range-init
1684 SourceLocation RangeLoc = Range->getLocStart();
1685 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1686 Context.getAutoRRefDeductType(),
1687 "__range");
1688 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1689 diag::err_for_range_deduction_failure))
1690 return StmtError();
1691
1692 // Claim the type doesn't contain auto: we've already done the checking.
1693 DeclGroupPtrTy RangeGroup =
1694 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1695 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1696 if (RangeDecl.isInvalid())
1697 return StmtError();
1698
1699 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1700 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smith8b533d92012-09-20 21:52:32 +00001701 RParenLoc, Kind);
Sam Panzere1715b62012-08-21 00:52:01 +00001702}
1703
1704/// \brief Create the initialization, compare, and increment steps for
1705/// the range-based for loop expression.
1706/// This function does not handle array-based for loops,
1707/// which are created in Sema::BuildCXXForRangeStmt.
1708///
1709/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1710/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1711/// CandidateSet and BEF are set and some non-success value is returned on
1712/// failure.
1713static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1714 Expr *BeginRange, Expr *EndRange,
1715 QualType RangeType,
1716 VarDecl *BeginVar,
1717 VarDecl *EndVar,
1718 SourceLocation ColonLoc,
1719 OverloadCandidateSet *CandidateSet,
1720 ExprResult *BeginExpr,
1721 ExprResult *EndExpr,
1722 Sema::BeginEndFunction *BEF) {
1723 DeclarationNameInfo BeginNameInfo(
1724 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1725 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1726 ColonLoc);
1727
1728 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1729 Sema::LookupMemberName);
1730 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1731
1732 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1733 // - if _RangeT is a class type, the unqualified-ids begin and end are
1734 // looked up in the scope of class _RangeT as if by class member access
1735 // lookup (3.4.5), and if either (or both) finds at least one
1736 // declaration, begin-expr and end-expr are __range.begin() and
1737 // __range.end(), respectively;
1738 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1739 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1740
1741 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1742 SourceLocation RangeLoc = BeginVar->getLocation();
1743 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1744
1745 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1746 << RangeLoc << BeginRange->getType() << *BEF;
1747 return Sema::FRS_DiagnosticIssued;
1748 }
1749 } else {
1750 // - otherwise, begin-expr and end-expr are begin(__range) and
1751 // end(__range), respectively, where begin and end are looked up with
1752 // argument-dependent lookup (3.4.2). For the purposes of this name
1753 // lookup, namespace std is an associated namespace.
1754
1755 }
1756
1757 *BEF = Sema::BEF_begin;
1758 Sema::ForRangeStatus RangeStatus =
1759 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1760 Sema::BEF_begin, BeginNameInfo,
1761 BeginMemberLookup, CandidateSet,
1762 BeginRange, BeginExpr);
1763
1764 if (RangeStatus != Sema::FRS_Success)
1765 return RangeStatus;
1766 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1767 diag::err_for_range_iter_deduction_failure)) {
1768 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1769 return Sema::FRS_DiagnosticIssued;
1770 }
1771
1772 *BEF = Sema::BEF_end;
1773 RangeStatus =
1774 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1775 Sema::BEF_end, EndNameInfo,
1776 EndMemberLookup, CandidateSet,
1777 EndRange, EndExpr);
1778 if (RangeStatus != Sema::FRS_Success)
1779 return RangeStatus;
1780 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1781 diag::err_for_range_iter_deduction_failure)) {
1782 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1783 return Sema::FRS_DiagnosticIssued;
1784 }
1785 return Sema::FRS_Success;
1786}
1787
1788/// Speculatively attempt to dereference an invalid range expression.
Richard Smith8b533d92012-09-20 21:52:32 +00001789/// If the attempt fails, this function will return a valid, null StmtResult
1790/// and emit no diagnostics.
Sam Panzere1715b62012-08-21 00:52:01 +00001791static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1792 SourceLocation ForLoc,
1793 Stmt *LoopVarDecl,
1794 SourceLocation ColonLoc,
1795 Expr *Range,
1796 SourceLocation RangeLoc,
1797 SourceLocation RParenLoc) {
Richard Smith8b533d92012-09-20 21:52:32 +00001798 // Determine whether we can rebuild the for-range statement with a
1799 // dereferenced range expression.
1800 ExprResult AdjustedRange;
1801 {
1802 Sema::SFINAETrap Trap(SemaRef);
1803
1804 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1805 if (AdjustedRange.isInvalid())
1806 return StmtResult();
1807
1808 StmtResult SR =
1809 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1810 AdjustedRange.get(), RParenLoc,
1811 Sema::BFRK_Check);
1812 if (SR.isInvalid())
1813 return StmtResult();
1814 }
1815
1816 // The attempt to dereference worked well enough that it could produce a valid
1817 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1818 // case there are any other (non-fatal) problems with it.
1819 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1820 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1821 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1822 AdjustedRange.get(), RParenLoc,
1823 Sema::BFRK_Rebuild);
Richard Smithad762fc2011-04-14 22:09:26 +00001824}
1825
Richard Smith8b533d92012-09-20 21:52:32 +00001826/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smithad762fc2011-04-14 22:09:26 +00001827StmtResult
1828Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1829 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1830 Expr *Inc, Stmt *LoopVarDecl,
Richard Smith8b533d92012-09-20 21:52:32 +00001831 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smithad762fc2011-04-14 22:09:26 +00001832 Scope *S = getCurScope();
1833
1834 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1835 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1836 QualType RangeVarType = RangeVar->getType();
1837
1838 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1839 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1840
1841 StmtResult BeginEndDecl = BeginEnd;
1842 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1843
1844 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1845 SourceLocation RangeLoc = RangeVar->getLocation();
1846
Ted Kremeneke50b0152011-10-10 22:36:28 +00001847 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1848
1849 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1850 VK_LValue, ColonLoc);
1851 if (BeginRangeRef.isInvalid())
1852 return StmtError();
1853
1854 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1855 VK_LValue, ColonLoc);
1856 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001857 return StmtError();
1858
1859 QualType AutoType = Context.getAutoDeductType();
1860 Expr *Range = RangeVar->getInit();
1861 if (!Range)
1862 return StmtError();
1863 QualType RangeType = Range->getType();
1864
1865 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001866 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001867 return StmtError();
1868
1869 // Build auto __begin = begin-expr, __end = end-expr.
1870 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1871 "__begin");
1872 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1873 "__end");
1874
1875 // Build begin-expr and end-expr and attach to __begin and __end variables.
1876 ExprResult BeginExpr, EndExpr;
1877 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1878 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1879 // __range + __bound, respectively, where __bound is the array bound. If
1880 // _RangeT is an array of unknown size or an array of incomplete type,
1881 // the program is ill-formed;
1882
1883 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001884 BeginExpr = BeginRangeRef;
1885 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001886 diag::err_for_range_iter_deduction_failure)) {
1887 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1888 return StmtError();
1889 }
1890
1891 // Find the array bound.
1892 ExprResult BoundExpr;
1893 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1894 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001895 Context.getPointerDiffType(),
1896 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001897 else if (const VariableArrayType *VAT =
1898 dyn_cast<VariableArrayType>(UnqAT))
1899 BoundExpr = VAT->getSizeExpr();
1900 else {
1901 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1902 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001903 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001904 }
1905
1906 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001907 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001908 BoundExpr.get());
1909 if (EndExpr.isInvalid())
1910 return StmtError();
1911 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1912 diag::err_for_range_iter_deduction_failure)) {
1913 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1914 return StmtError();
1915 }
1916 } else {
Sam Panzere1715b62012-08-21 00:52:01 +00001917 OverloadCandidateSet CandidateSet(RangeLoc);
1918 Sema::BeginEndFunction BEFFailure;
1919 ForRangeStatus RangeStatus =
1920 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1921 EndRangeRef.get(), RangeType,
1922 BeginVar, EndVar, ColonLoc, &CandidateSet,
1923 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smithad762fc2011-04-14 22:09:26 +00001924
Sam Panzere1715b62012-08-21 00:52:01 +00001925 // If building the range failed, try dereferencing the range expression
1926 // unless a diagnostic was issued or the end function is problematic.
Richard Smith8b533d92012-09-20 21:52:32 +00001927 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzere1715b62012-08-21 00:52:01 +00001928 BEFFailure == BEF_begin) {
1929 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1930 LoopVarDecl, ColonLoc,
1931 Range, RangeLoc,
1932 RParenLoc);
Richard Smith8b533d92012-09-20 21:52:32 +00001933 if (SR.isInvalid() || SR.isUsable())
Sam Panzere1715b62012-08-21 00:52:01 +00001934 return SR;
Richard Smithad762fc2011-04-14 22:09:26 +00001935 }
1936
Sam Panzere1715b62012-08-21 00:52:01 +00001937 // Otherwise, emit diagnostics if we haven't already.
1938 if (RangeStatus == FRS_NoViableFunction) {
Richard Smith8b533d92012-09-20 21:52:32 +00001939 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzere1715b62012-08-21 00:52:01 +00001940 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1941 << RangeLoc << Range->getType() << BEFFailure;
Nico Weberd36aa352012-12-29 20:03:39 +00001942 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzere1715b62012-08-21 00:52:01 +00001943 }
1944 // Return an error if no fix was discovered.
1945 if (RangeStatus != FRS_Success)
Richard Smithad762fc2011-04-14 22:09:26 +00001946 return StmtError();
1947 }
1948
Sam Panzere1715b62012-08-21 00:52:01 +00001949 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1950 "invalid range expression in for loop");
1951
1952 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smithad762fc2011-04-14 22:09:26 +00001953 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1954 if (!Context.hasSameType(BeginType, EndType)) {
1955 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1956 << BeginType << EndType;
1957 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1958 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1959 }
1960
1961 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1962 // Claim the type doesn't contain auto: we've already done the checking.
1963 DeclGroupPtrTy BeginEndGroup =
1964 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1965 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1966
Ted Kremeneke50b0152011-10-10 22:36:28 +00001967 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1968 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001969 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001970 if (BeginRef.isInvalid())
1971 return StmtError();
1972
Richard Smithad762fc2011-04-14 22:09:26 +00001973 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1974 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001975 if (EndRef.isInvalid())
1976 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001977
1978 // Build and check __begin != __end expression.
1979 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1980 BeginRef.get(), EndRef.get());
1981 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1982 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1983 if (NotEqExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00001984 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1985 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00001986 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1987 if (!Context.hasSameType(BeginType, EndType))
1988 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1989 return StmtError();
1990 }
1991
1992 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001993 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1994 VK_LValue, ColonLoc);
1995 if (BeginRef.isInvalid())
1996 return StmtError();
1997
Richard Smithad762fc2011-04-14 22:09:26 +00001998 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1999 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2000 if (IncrExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002001 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2002 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smithad762fc2011-04-14 22:09:26 +00002003 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2004 return StmtError();
2005 }
2006
2007 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00002008 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2009 VK_LValue, ColonLoc);
2010 if (BeginRef.isInvalid())
2011 return StmtError();
2012
Richard Smithad762fc2011-04-14 22:09:26 +00002013 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2014 if (DerefExpr.isInvalid()) {
Sam Panzer8123b6e2012-09-06 21:50:08 +00002015 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2016 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smithad762fc2011-04-14 22:09:26 +00002017 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2018 return StmtError();
2019 }
2020
Richard Smith8b533d92012-09-20 21:52:32 +00002021 // Attach *__begin as initializer for VD. Don't touch it if we're just
2022 // trying to determine whether this would be a valid range.
2023 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smithad762fc2011-04-14 22:09:26 +00002024 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2025 /*TypeMayContainAuto=*/true);
2026 if (LoopVar->isInvalidDecl())
2027 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2028 }
Richard Smithcd6f3662011-06-21 23:07:19 +00002029 } else {
2030 // The range is implicitly used as a placeholder when it is dependent.
2031 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00002032 }
2033
Richard Smith8b533d92012-09-20 21:52:32 +00002034 // Don't bother to actually allocate the result if we're just trying to
2035 // determine whether it would be valid.
2036 if (Kind == BFRK_Check)
2037 return StmtResult();
2038
Richard Smithad762fc2011-04-14 22:09:26 +00002039 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2040 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2041 NotEqExpr.take(), IncrExpr.take(),
2042 LoopVarDS, /*Body=*/0, ForLoc,
2043 ColonLoc, RParenLoc));
2044}
2045
Chad Rosier1093f492012-08-10 17:56:09 +00002046/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002047/// statement.
2048StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2049 if (!S || !B)
2050 return StmtError();
2051 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier1093f492012-08-10 17:56:09 +00002052
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00002053 ForStmt->setBody(B);
2054 return S;
2055}
2056
Richard Smithad762fc2011-04-14 22:09:26 +00002057/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2058/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2059/// body cannot be performed until after the type of the range variable is
2060/// determined.
2061StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2062 if (!S || !B)
2063 return StmtError();
2064
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00002065 if (isa<ObjCForCollectionStmt>(S))
2066 return FinishObjCForCollectionStmt(S, B);
Chad Rosier1093f492012-08-10 17:56:09 +00002067
Dmitri Gribenko625bb562012-02-14 22:14:32 +00002068 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2069 ForStmt->setBody(B);
2070
2071 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2072 diag::warn_empty_range_based_for_body);
2073
Richard Smithad762fc2011-04-14 22:09:26 +00002074 return S;
2075}
2076
Chris Lattner57ad3782011-02-17 20:34:02 +00002077StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2078 SourceLocation LabelLoc,
2079 LabelDecl *TheDecl) {
2080 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002081 TheDecl->setUsed();
2082 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002083}
2084
John McCall60d7b3a2010-08-24 06:29:42 +00002085StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002086Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002087 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002088 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002089 if (!E->isTypeDependent()) {
2090 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002091 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002092 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002093 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002094 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2095 if (ExprRes.isInvalid())
2096 return StmtError();
2097 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002098 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002099 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00002100 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002101 }
John McCallb60a77e2010-08-01 00:26:45 +00002102
John McCall781472f2010-08-25 08:40:02 +00002103 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002104
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002105 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002106}
2107
John McCall60d7b3a2010-08-24 06:29:42 +00002108StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002109Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 Scope *S = CurScope->getContinueParent();
2111 if (!S) {
2112 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002113 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002115
Ted Kremenek8189cde2009-02-07 01:47:29 +00002116 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002117}
2118
John McCall60d7b3a2010-08-24 06:29:42 +00002119StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002120Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 Scope *S = CurScope->getBreakParent();
2122 if (!S) {
2123 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002124 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002126
Ted Kremenek8189cde2009-02-07 01:47:29 +00002127 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002128}
2129
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002131/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002132///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002133/// \param ReturnType If we're determining the copy elision candidate for
2134/// a return statement, this is the return type of the function. If we're
2135/// determining the copy elision candidate for a throw expression, this will
2136/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002137///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002138/// \param E The expression being returned from the function or block, or
2139/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002140///
Douglas Gregor4926d832011-05-20 15:00:53 +00002141/// \param AllowFunctionParameter Whether we allow function parameters to
2142/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2143/// we re-use this logic to determine whether we should try to move as part of
2144/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002145///
2146/// \returns The NRVO candidate variable, if the return statement may use the
2147/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002148const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2149 Expr *E,
2150 bool AllowFunctionParameter) {
2151 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002152 // - in a return statement in a function with ...
2153 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002154 if (!ReturnType.isNull()) {
2155 if (!ReturnType->isRecordType())
2156 return 0;
2157 // ... the same cv-unqualified type as the function return type ...
2158 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2159 return 0;
2160 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161
2162 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002163 // (other than a function or catch-clause parameter)) ...
2164 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002165 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002166 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002167 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2168 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002169 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170
John McCall1cd76e82011-11-11 03:57:31 +00002171 // ...object (other than a function or catch-clause parameter)...
2172 if (VD->getKind() != Decl::Var &&
2173 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2174 return 0;
2175 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002176
John McCall1cd76e82011-11-11 03:57:31 +00002177 // ...automatic...
2178 if (!VD->hasLocalStorage()) return 0;
2179
2180 // ...non-volatile...
2181 if (VD->getType().isVolatileQualified()) return 0;
2182 if (VD->getType()->isReferenceType()) return 0;
2183
2184 // __block variables can't be allocated in a way that permits NRVO.
2185 if (VD->hasAttr<BlocksAttr>()) return 0;
2186
2187 // Variables with higher required alignment than their type's ABI
2188 // alignment cannot use NRVO.
2189 if (VD->hasAttr<AlignedAttr>() &&
2190 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2191 return 0;
2192
2193 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002194}
2195
Douglas Gregor07f402c2011-01-21 21:08:57 +00002196/// \brief Perform the initialization of a potentially-movable value, which
2197/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002198///
2199/// This routine implements C++0x [class.copy]p33, which attempts to treat
2200/// returned lvalues as rvalues in certain cases (to prefer move construction),
2201/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002202ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002203Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2204 const VarDecl *NRVOCandidate,
2205 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002206 Expr *Value,
2207 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002208 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 // When the criteria for elision of a copy operation are met or would
2210 // be met save for the fact that the source object is a function
2211 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002212 // overload resolution to select the constructor for the copy is first
2213 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002214 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002215 if (AllowNRVO &&
2216 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002217 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002218 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Douglas Gregorcc15f012011-01-21 19:38:21 +00002220 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002222 = InitializationKind::CreateCopy(Value->getLocStart(),
2223 Value->getLocStart());
2224 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225
2226 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002227 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002228 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002229 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002230 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002231 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2232 StepEnd = Seq.step_end();
2233 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002234 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002235 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002236
2237 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002238 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002239
Douglas Gregorcc15f012011-01-21 19:38:21 +00002240 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002241 = Constructor->getParamDecl(0)->getType()
2242 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002243
Douglas Gregorcc15f012011-01-21 19:38:21 +00002244 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002245 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002246 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2247 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002248 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002249
Douglas Gregorcc15f012011-01-21 19:38:21 +00002250 // Promote "AsRvalue" to the heap, since we now need this
2251 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002252 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002253 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002254
Douglas Gregorcc15f012011-01-21 19:38:21 +00002255 // Complete type-checking the initialization of the return type
2256 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002257 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002258 }
2259 }
2260 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002261
Douglas Gregorcc15f012011-01-21 19:38:21 +00002262 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002264 // (again) now with the return value expression as written.
2265 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002266 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267
Douglas Gregorcc15f012011-01-21 19:38:21 +00002268 return Res;
2269}
2270
Eli Friedman84b007f2012-01-26 03:00:14 +00002271/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2272/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002273///
John McCall60d7b3a2010-08-24 06:29:42 +00002274StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002275Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2276 // If this is the first return we've seen, infer the return type.
2277 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2278 // rules which allows multiple return statements.
2279 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002280 QualType FnRetType = CurCap->ReturnType;
2281
2282 // For blocks/lambdas with implicit return types, we check each return
2283 // statement individually, and deduce the common return type when the block
2284 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002285 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002286 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002287 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2288 if (Result.isInvalid())
2289 return StmtError();
2290 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002291
Jordan Rose7dd900e2012-07-02 21:19:23 +00002292 if (!RetValExp->isTypeDependent())
2293 FnRetType = RetValExp->getType();
2294 else
2295 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier1093f492012-08-10 17:56:09 +00002296 } else {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002297 if (RetValExp) {
2298 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2299 // initializer list, because it is not an expression (even
2300 // though we represent it as one). We still deduce 'void'.
2301 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2302 << RetValExp->getSourceRange();
2303 }
2304
Jordan Rose7dd900e2012-07-02 21:19:23 +00002305 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002306 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002307
2308 // Although we'll properly infer the type of the block once it's completed,
2309 // make sure we provide a return type now for better error recovery.
2310 if (CurCap->ReturnType.isNull())
2311 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002312 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002313 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002314
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002315 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002316 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2317 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2318 return StmtError();
2319 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002320 } else {
2321 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2322 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2323 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2324 return StmtError();
2325 }
2326 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002327
Steve Naroff4eb206b2008-09-03 18:15:37 +00002328 // Otherwise, verify that this result type matches the previous one. We are
2329 // pickier with blocks than for normal functions because we don't have GCC
2330 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002331 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002332 if (FnRetType->isDependentType()) {
2333 // Delay processing for now. TODO: there are lots of dependent
2334 // types we can conclusively prove aren't void.
2335 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002336 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002337 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002338 (RetValExp->isTypeDependent() ||
2339 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002340 if (!getLangOpts().CPlusPlus &&
2341 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002342 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002343 else {
2344 Diag(ReturnLoc, diag::err_return_block_has_expr);
2345 RetValExp = 0;
2346 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002347 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002348 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002349 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2350 } else if (!RetValExp->isTypeDependent()) {
2351 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002352
John McCall0a7efe12011-08-17 22:09:46 +00002353 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2354 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2355 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002356
John McCall0a7efe12011-08-17 22:09:46 +00002357 // In C++ the return statement is handled via a copy initialization.
2358 // the C version of which boils down to CheckSingleAssignmentConstraints.
2359 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2360 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2361 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002362 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002363 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2364 FnRetType, RetValExp);
2365 if (Res.isInvalid()) {
2366 // FIXME: Cleanup temporaries here, anyway?
2367 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002368 }
John McCall0a7efe12011-08-17 22:09:46 +00002369 RetValExp = Res.take();
2370 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002371 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002372
John McCalld963c372011-08-17 21:34:14 +00002373 if (RetValExp) {
2374 CheckImplicitConversions(RetValExp, ReturnLoc);
2375 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2376 }
John McCall0a7efe12011-08-17 22:09:46 +00002377 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2378 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002379
Jordan Rose7dd900e2012-07-02 21:19:23 +00002380 // If we need to check for the named return value optimization,
2381 // or if we need to infer the return type,
2382 // save the return statement in our scope for later processing.
2383 if (CurCap->HasImplicitReturnType ||
2384 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2385 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002386 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002387
Douglas Gregor5077c382010-05-15 06:01:05 +00002388 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002389}
Reid Spencer5f016e22007-07-11 17:01:13 +00002390
John McCall60d7b3a2010-08-24 06:29:42 +00002391StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002392Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002393 // Check for unexpanded parameter packs.
2394 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2395 return StmtError();
Chad Rosier1093f492012-08-10 17:56:09 +00002396
Eli Friedman84b007f2012-01-26 03:00:14 +00002397 if (isa<CapturingScopeInfo>(getCurFunction()))
2398 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002399
Chris Lattner371f2582008-12-04 23:50:19 +00002400 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002401 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002402 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002403 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002404 if (FD->hasAttr<NoReturnAttr>() ||
2405 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002406 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002407 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002408 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002409 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002410 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2411 // In the implementation of a method with a related return type, the
Chad Rosier1093f492012-08-10 17:56:09 +00002412 // type used to type-check the validity of return statements within the
Douglas Gregor926df6c2011-06-11 01:09:30 +00002413 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002414 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2415 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002416 }
2417 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002418 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Douglas Gregor5077c382010-05-15 06:01:05 +00002420 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002421 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002422 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002423 if (isa<InitListExpr>(RetValExp)) {
2424 // We simply never allow init lists as the return value of void
2425 // functions. This is compatible because this was never allowed before,
2426 // so there's no legacy code to deal with.
2427 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2428 int FunctionKind = 0;
2429 if (isa<ObjCMethodDecl>(CurDecl))
2430 FunctionKind = 1;
2431 else if (isa<CXXConstructorDecl>(CurDecl))
2432 FunctionKind = 2;
2433 else if (isa<CXXDestructorDecl>(CurDecl))
2434 FunctionKind = 3;
2435
2436 Diag(ReturnLoc, diag::err_return_init_list)
2437 << CurDecl->getDeclName() << FunctionKind
2438 << RetValExp->getSourceRange();
2439
2440 // Drop the expression.
2441 RetValExp = 0;
2442 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002443 // C99 6.8.6.4p1 (ext_ since GCC warns)
2444 unsigned D = diag::ext_return_has_expr;
2445 if (RetValExp->getType()->isVoidType())
2446 D = diag::ext_return_has_void_expr;
2447 else {
2448 ExprResult Result = Owned(RetValExp);
2449 Result = IgnoredValueConversions(Result.take());
2450 if (Result.isInvalid())
2451 return StmtError();
2452 RetValExp = Result.take();
2453 RetValExp = ImpCastExprToType(RetValExp,
2454 Context.VoidTy, CK_ToVoid).take();
2455 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002456
Nick Lewycky8d794612011-06-01 07:44:31 +00002457 // return (some void expression); is legal in C++.
2458 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002459 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002460 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002461
2462 int FunctionKind = 0;
2463 if (isa<ObjCMethodDecl>(CurDecl))
2464 FunctionKind = 1;
2465 else if (isa<CXXConstructorDecl>(CurDecl))
2466 FunctionKind = 2;
2467 else if (isa<CXXDestructorDecl>(CurDecl))
2468 FunctionKind = 3;
2469
Nick Lewycky8d794612011-06-01 07:44:31 +00002470 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002471 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002472 << RetValExp->getSourceRange();
2473 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002474 }
Mike Stump1eb44332009-09-09 15:08:12 +00002475
Sebastian Redl33deb352012-02-22 10:50:08 +00002476 if (RetValExp) {
2477 CheckImplicitConversions(RetValExp, ReturnLoc);
2478 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2479 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002481
Douglas Gregor5077c382010-05-15 06:01:05 +00002482 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2483 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002484 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2485 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002486 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002487
2488 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002489 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002490 else
Chris Lattner08631c52008-11-23 21:45:46 +00002491 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002492 Result = new (Context) ReturnStmt(ReturnLoc);
2493 } else {
2494 const VarDecl *NRVOCandidate = 0;
2495 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2496 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002497
Eli Friedman38ac2432012-03-30 01:13:43 +00002498 if (!RelatedRetType.isNull()) {
2499 // If we have a related result type, perform an extra conversion here.
2500 // FIXME: The diagnostics here don't really describe what is happening.
2501 InitializedEntity Entity =
2502 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002503
Eli Friedman38ac2432012-03-30 01:13:43 +00002504 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2505 RetValExp);
2506 if (Res.isInvalid()) {
2507 // FIXME: Cleanup temporaries here, anyway?
2508 return StmtError();
2509 }
2510 RetValExp = Res.takeAs<Expr>();
2511 }
2512
Douglas Gregor5077c382010-05-15 06:01:05 +00002513 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2514 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2515 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002516
John McCall856d3792011-06-16 23:24:51 +00002517 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002518 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002519 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002520 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002521 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002522 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002523 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002524 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002525 if (Res.isInvalid()) {
2526 // FIXME: Cleanup temporaries here, anyway?
2527 return StmtError();
2528 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002529
Douglas Gregor5077c382010-05-15 06:01:05 +00002530 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002531 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002532 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002533 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002534
John McCallb4eb64d2010-10-08 02:01:28 +00002535 if (RetValExp) {
2536 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002537 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002538 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002539 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002540 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541
2542 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002543 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002544 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002545 !CurContext->isDependentContext())
2546 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002547
Douglas Gregor5077c382010-05-15 06:01:05 +00002548 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002549}
2550
John McCall60d7b3a2010-08-24 06:29:42 +00002551StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002552Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002553 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002554 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002555 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002556 if (Var && Var->isInvalidDecl())
2557 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558
John McCall9ae2f072010-08-23 23:25:46 +00002559 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002560}
2561
John McCall60d7b3a2010-08-24 06:29:42 +00002562StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002563Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2564 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002565}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002566
John McCall60d7b3a2010-08-24 06:29:42 +00002567StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002568Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002569 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002570 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002571 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2572
John McCall781472f2010-08-25 08:40:02 +00002573 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002574 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002575 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002576 CatchStmts.data(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002577 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002578 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002579}
2580
John McCalld1376ee2012-05-08 21:41:25 +00002581StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002582 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002583 ExprResult Result = DefaultLvalueConversion(Throw);
2584 if (Result.isInvalid())
2585 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002586
John McCalld1376ee2012-05-08 21:41:25 +00002587 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002588 QualType ThrowType = Throw->getType();
2589 // Make sure the expression type is an ObjC pointer or "void *".
2590 if (!ThrowType->isDependentType() &&
2591 !ThrowType->isObjCObjectPointerType()) {
2592 const PointerType *PT = ThrowType->getAs<PointerType>();
2593 if (!PT || !PT->getPointeeType()->isVoidType())
2594 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2595 << Throw->getType() << Throw->getSourceRange());
2596 }
2597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002598
John McCall9ae2f072010-08-23 23:25:46 +00002599 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002600}
2601
John McCall60d7b3a2010-08-24 06:29:42 +00002602StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002603Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002604 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002605 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002606 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2607
John McCall9ae2f072010-08-23 23:25:46 +00002608 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002609 // @throw without an expression designates a rethrow (which much occur
2610 // in the context of an @catch clause).
2611 Scope *AtCatchParent = CurScope;
2612 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2613 AtCatchParent = AtCatchParent->getParent();
2614 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002615 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002616 }
John McCall9ae2f072010-08-23 23:25:46 +00002617 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002618}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002619
John McCall07524032011-07-27 21:50:02 +00002620ExprResult
2621Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2622 ExprResult result = DefaultLvalueConversion(operand);
2623 if (result.isInvalid())
2624 return ExprError();
2625 operand = result.take();
2626
2627 // Make sure the expression type is an ObjC pointer or "void *".
2628 QualType type = operand->getType();
2629 if (!type->isDependentType() &&
2630 !type->isObjCObjectPointerType()) {
2631 const PointerType *pointerType = type->getAs<PointerType>();
2632 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2633 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2634 << type << operand->getSourceRange();
2635 }
2636
2637 // The operand to @synchronized is a full-expression.
2638 return MaybeCreateExprWithCleanups(operand);
2639}
2640
John McCall60d7b3a2010-08-24 06:29:42 +00002641StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002642Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2643 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002644 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002645 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002646 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002647}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002648
2649/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2650/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002651StmtResult
John McCalld226f652010-08-21 09:40:31 +00002652Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002653 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002654 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002655 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002656 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002657 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002658}
Sebastian Redl8351da02008-12-22 21:35:02 +00002659
John McCallf85e1932011-06-15 23:02:42 +00002660StmtResult
2661Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2662 getCurFunction()->setHasBranchProtectedScope();
2663 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2664}
2665
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002666namespace {
2667
Sebastian Redlc447aba2009-07-29 17:15:45 +00002668class TypeWithHandler {
2669 QualType t;
2670 CXXCatchStmt *stmt;
2671public:
2672 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2673 : t(type), stmt(statement) {}
2674
John McCall0953e762009-09-24 19:53:00 +00002675 // An arbitrary order is fine as long as it places identical
2676 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002677 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002678 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002679 return true;
John McCall0953e762009-09-24 19:53:00 +00002680 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002681 return false;
2682 else
2683 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2684 }
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Sebastian Redlc447aba2009-07-29 17:15:45 +00002686 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002687 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002688 }
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Sebastian Redlc447aba2009-07-29 17:15:45 +00002690 CXXCatchStmt *getCatchStmt() const { return stmt; }
2691 SourceLocation getTypeSpecStartLoc() const {
2692 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2693 }
2694};
2695
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002696}
2697
Sebastian Redl8351da02008-12-22 21:35:02 +00002698/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2699/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002700StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002701Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002702 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002703 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002704 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002705 !getSourceManager().isInSystemHeader(TryLoc))
2706 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002707
Sebastian Redl8351da02008-12-22 21:35:02 +00002708 unsigned NumHandlers = RawHandlers.size();
2709 assert(NumHandlers > 0 &&
2710 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramer5354e772012-08-23 23:38:35 +00002711 Stmt **Handlers = RawHandlers.data();
Sebastian Redl8351da02008-12-22 21:35:02 +00002712
Chris Lattner5f9e2722011-07-23 10:55:15 +00002713 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002714
2715 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002716 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002717 if (!Handler->getExceptionDecl()) {
2718 if (i < NumHandlers - 1)
2719 return StmtError(Diag(Handler->getLocStart(),
2720 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Sebastian Redlc447aba2009-07-29 17:15:45 +00002722 continue;
2723 }
Mike Stump1eb44332009-09-09 15:08:12 +00002724
Sebastian Redlc447aba2009-07-29 17:15:45 +00002725 const QualType CaughtType = Handler->getCaughtType();
2726 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2727 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002728 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002729
2730 // Detect handlers for the same type as an earlier one.
2731 if (NumHandlers > 1) {
2732 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Sebastian Redlc447aba2009-07-29 17:15:45 +00002734 TypeWithHandler prev = TypesWithHandlers[0];
2735 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2736 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Sebastian Redlc447aba2009-07-29 17:15:45 +00002738 if (curr == prev) {
2739 Diag(curr.getTypeSpecStartLoc(),
2740 diag::warn_exception_caught_by_earlier_handler)
2741 << curr.getCatchStmt()->getCaughtType().getAsString();
2742 Diag(prev.getTypeSpecStartLoc(),
2743 diag::note_previous_exception_handler)
2744 << prev.getCatchStmt()->getCaughtType().getAsString();
2745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Sebastian Redlc447aba2009-07-29 17:15:45 +00002747 prev = curr;
2748 }
2749 }
Mike Stump1eb44332009-09-09 15:08:12 +00002750
John McCall781472f2010-08-25 08:40:02 +00002751 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002752
Sebastian Redl8351da02008-12-22 21:35:02 +00002753 // FIXME: We should detect handlers that cannot catch anything because an
2754 // earlier handler catches a superclass. Need to find a method that is not
2755 // quadratic for this.
2756 // Neither of these are explicitly forbidden, but every compiler detects them
2757 // and warns.
2758
John McCall9ae2f072010-08-23 23:25:46 +00002759 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Nico Weber07cf58c2012-12-29 20:13:03 +00002760 llvm::makeArrayRef(Handlers, NumHandlers)));
Sebastian Redl8351da02008-12-22 21:35:02 +00002761}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002762
2763StmtResult
2764Sema::ActOnSEHTryBlock(bool IsCXXTry,
2765 SourceLocation TryLoc,
2766 Stmt *TryBlock,
2767 Stmt *Handler) {
2768 assert(TryBlock && Handler);
2769
2770 getCurFunction()->setHasBranchProtectedScope();
2771
2772 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2773}
2774
2775StmtResult
2776Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2777 Expr *FilterExpr,
2778 Stmt *Block) {
2779 assert(FilterExpr && Block);
2780
2781 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002782 return StmtError(Diag(FilterExpr->getExprLoc(),
2783 diag::err_filter_expression_integral)
2784 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002785 }
2786
2787 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2788}
2789
2790StmtResult
2791Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2792 Stmt *Block) {
2793 assert(Block);
2794 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2795}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002796
2797StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2798 bool IsIfExists,
2799 NestedNameSpecifierLoc QualifierLoc,
2800 DeclarationNameInfo NameInfo,
2801 Stmt *Nested)
2802{
2803 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002804 QualifierLoc, NameInfo,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002805 cast<CompoundStmt>(Nested));
2806}
2807
2808
Chad Rosier1093f492012-08-10 17:56:09 +00002809StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002810 bool IsIfExists,
Chad Rosier1093f492012-08-10 17:56:09 +00002811 CXXScopeSpec &SS,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002812 UnqualifiedId &Name,
2813 Stmt *Nested) {
Chad Rosier1093f492012-08-10 17:56:09 +00002814 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregorba0513d2011-10-25 01:33:02 +00002815 SS.getWithLocInContext(Context),
2816 GetNameFromUnqualifiedId(Name),
2817 Nested);
2818}