blob: 472338a541a8be278f0a5e1022d2d62f4a35228f [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
John McCall03318c12011-11-11 03:57:31 +000016#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000020#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000023#include "clang/AST/TypeLoc.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-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 Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000035using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000036using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000037
John McCalldadc5752010-08-24 06:29:42 +000038StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000039 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000040 if (!E) // FIXME: FullExprArg has no error state?
41 return StmtError();
42
Chris Lattner903eb512008-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 Redl52f03ba2008-12-21 12:04:03 +000046
Chris Lattner903eb512008-07-25 23:18:17 +000047 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000048 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000049}
50
51
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000052StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000053 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000055}
56
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000057StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnercbafe8d2009-04-12 20:13:14 +000061 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner34a22092009-03-04 04:23:07 +000064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000065}
Chris Lattneraf8d5812006-11-10 05:07:45 +000066
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000067void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000069
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000070 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000074 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000075 var->setUsed();
76
John McCalld4631322011-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 McCall31168b02011-06-15 23:02:42 +000080
John McCalld4631322011-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 Blaikiebbafb8a2012-03-11 07:00:24 +000084 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-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 McCall31168b02011-06-15 23:02:42 +000094 }
95 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000096}
97
Chandler Carruthe2669392011-08-17 09:34:37 +000098/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +000099///
100/// Adding a cast to void (or other expression wrappers) will prevent the
101/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000102static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000103 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000104 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000108 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000109
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000110 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000116 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000117
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000118 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000121 } else {
122 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123 return false;
Chandler Carruthae51ecc2011-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 Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Chandler Carruthe2669392011-08-17 09:34:37 +0000131 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 << (unsigned)IsNotEqual << E->getSourceRange();
133
Chandler Carruthe89ca5f2011-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 Carruthe2669392011-08-17 09:34:37 +0000144
145 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000146}
147
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000148void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
151
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000152 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000153 if (!E)
154 return;
155
Eli Friedmanc11535c2012-05-24 00:47:05 +0000156 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000157 SourceLocation Loc;
158 SourceRange R1, R2;
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +0000159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmanc11535c2012-05-24 00:47:05 +0000160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000161 return;
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattner6dc7e572012-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 Lattner2ba5ca92009-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 McCall5d413782010-12-06 08:20:24 +0000174 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000175 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000176 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
177 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000178
Chandler Carruthe2669392011-08-17 09:34:37 +0000179 if (DiagnoseUnusedComparison(*this, E))
180 return;
181
Eli Friedmanc11535c2012-05-24 00:47:05 +0000182 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000183 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000184 if (E->getType()->isVoidType())
185 return;
186
Chris Lattner1a6babf2009-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 Lopes518e3702009-12-20 23:11:08 +0000189 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000190 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000191 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-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 Takumif9cbcc42011-01-27 07:10:08 +0000202 }
John McCallb7bd14f2010-12-02 01:19:52 +0000203 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000204 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000205 Diag(Loc, diag::err_arc_unused_init_message) << R1;
206 return;
207 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000208 const ObjCMethodDecl *MD = ME->getMethodDecl();
209 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000210 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000211 return;
212 }
Ted Kremeneke65b0862012-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 Gregorb33eed02010-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 Jahanian5cab26d2010-03-30 18:22:15 +0000224 }
John McCall2351cb92010-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 Friedmanc11535c2012-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 Kremenek3427fac2011-02-23 01:52:04 +0000245 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000246}
247
Dmitri Gribenko800ddf32012-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 McCalldadc5752010-08-24 06:29:42 +0000260StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000261Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000262 MultiStmtArg elts, bool isStmtExpr) {
263 unsigned NumElts = elts.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000264 Stmt **Elts = elts.data();
Chris Lattnerd864daf2007-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000267 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-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 Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattnerd864daf2007-08-27 04:29:41 +0000278 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000279 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000280 Diag(D->getLocation(), diag::ext_mixed_decls_code);
281 }
282 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000283 // Warn about unused expressions in statements.
284 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000285 // Ignore statements that are last in a statement expression.
286 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000287 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000288
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000289 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000290 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000291
Dmitri Gribenko800ddf32012-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
Ted Kremenek5a201952009-02-07 01:47:29 +0000301 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000302}
303
John McCalldadc5752010-08-24 06:29:42 +0000304StmtResult
John McCallb268a282010-08-23 23:25:46 +0000305Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
306 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000307 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000308 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000309
John McCallaab3e412010-08-25 08:40:02 +0000310 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000311 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000312 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000313 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000314
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 if (!getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000316 // C99 6.8.4.2p3: The expression shall be an integer constant.
317 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000318 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
319 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
320 if (!LHSVal)
321 return StmtError();
322 }
Richard Smithf8379a02012-01-18 23:55:52 +0000323
324 // GCC extension: The expression shall be an integer constant.
325
Richard Smithf4c51d92012-02-04 09:53:13 +0000326 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
327 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
328 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000329 }
330 }
331
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000332 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
333 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000334 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000335 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000336}
337
Chris Lattner34a22092009-03-04 04:23:07 +0000338/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000339void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000340 DiagnoseUnusedExprResult(SubStmt);
341
Chris Lattner34a22092009-03-04 04:23:07 +0000342 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000343 CS->setSubStmt(SubStmt);
344}
345
John McCalldadc5752010-08-24 06:29:42 +0000346StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000347Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000348 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000349 DiagnoseUnusedExprResult(SubStmt);
350
John McCallaab3e412010-08-25 08:40:02 +0000351 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000352 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000353 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000354 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000355
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000356 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000357 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000358 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000359}
360
John McCalldadc5752010-08-24 06:29:42 +0000361StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000362Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
363 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000364 // If the label was multiply defined, reject it now.
365 if (TheDecl->getStmt()) {
366 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
367 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000368 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000369 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000370
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000371 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000372 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
373 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000374 if (!TheDecl->isGnuLocal()) {
375 TheDecl->setLocStart(IdentLoc);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000376 TheDecl->setLocation(IdentLoc);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000377 }
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000378 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000379}
380
Richard Smithc202b282012-04-14 00:33:13 +0000381StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000382 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000383 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000384 // Fill in the declaration and return it.
385 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smithc202b282012-04-14 00:33:13 +0000386 return Owned(LS);
387}
388
John McCalldadc5752010-08-24 06:29:42 +0000389StmtResult
John McCall48871652010-08-21 09:40:31 +0000390Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000391 Stmt *thenStmt, SourceLocation ElseLoc,
392 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000393 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregor633caca2009-11-23 23:44:04 +0000395 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000396 if (CondVar) {
397 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000398 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000399 if (CondResult.isInvalid())
400 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000401 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000402 Expr *ConditionExpr = CondResult.takeAs<Expr>();
403 if (!ConditionExpr)
404 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000406 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000407
John McCallb268a282010-08-23 23:25:46 +0000408 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000409 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
410 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000411 }
412
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000413 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000416 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000417}
Steve Naroff86272ea2007-05-29 02:14:17 +0000418
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000419/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
420/// the specified width and sign. If an overflow occurs, detect it and emit
421/// the specified diagnostic.
422void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
423 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000424 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000425 unsigned DiagID) {
426 // Perform a conversion to the promoted condition type if needed.
427 if (NewWidth > Val.getBitWidth()) {
428 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000429 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000430 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000431
432 // If the input was signed and negative and the output is
433 // unsigned, don't bother to warn: this is implementation-defined
434 // behavior.
435 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000436 } else if (NewWidth < Val.getBitWidth()) {
437 // If this is a truncation, check for overflow.
438 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000439 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000440 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000441 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000442 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000443 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000444 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000445
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000446 // Regardless of whether a diagnostic was emitted, really do the
447 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000448 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000449 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000450 } else if (NewSign != Val.isSigned()) {
451 // Convert the sign to match the sign of the condition. This can cause
452 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000454 // behavior.
455 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000456 llvm::APSInt OldVal(Val);
457 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000458 }
459}
460
Chris Lattner67998452007-08-23 18:29:20 +0000461namespace {
462 struct CaseCompareFunctor {
463 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
464 const llvm::APSInt &RHS) {
465 return LHS.first < RHS;
466 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000467 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
468 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
469 return LHS.first < RHS.first;
470 }
Chris Lattner67998452007-08-23 18:29:20 +0000471 bool operator()(const llvm::APSInt &LHS,
472 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
473 return LHS < RHS.first;
474 }
475 };
476}
477
Chris Lattner4b2ff022007-09-21 18:15:22 +0000478/// CmpCaseVals - Comparison predicate for sorting case values.
479///
480static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
481 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
482 if (lhs.first < rhs.first)
483 return true;
484
485 if (lhs.first == rhs.first &&
486 lhs.second->getCaseLoc().getRawEncoding()
487 < rhs.second->getCaseLoc().getRawEncoding())
488 return true;
489 return false;
490}
491
Douglas Gregorbd6839732010-02-08 22:24:16 +0000492/// CmpEnumVals - Comparison predicate for sorting enumeration values.
493///
494static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
495 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
496{
497 return lhs.first < rhs.first;
498}
499
500/// EqEnumVals - Comparison preficate for uniqing enumeration values.
501///
502static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
503 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
504{
505 return lhs.first == rhs.first;
506}
507
Chris Lattnera96d4272009-10-16 16:45:22 +0000508/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
509/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000510static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
511 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
512 expr = cleanups->getSubExpr();
513 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
514 if (impcast->getCastKind() != CK_IntegralCast) break;
515 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000516 }
517 return expr->getType();
518}
519
John McCalldadc5752010-08-24 06:29:42 +0000520StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000522 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000523 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000524
Douglas Gregore60e41a2010-05-06 17:25:47 +0000525 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000526 if (CondVar) {
527 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000528 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
529 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000530 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
John McCallb268a282010-08-23 23:25:46 +0000532 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
John McCallb268a282010-08-23 23:25:46 +0000535 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000536 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
Douglas Gregore2b37442012-05-04 22:38:52 +0000538 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
539 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000540
Douglas Gregore2b37442012-05-04 22:38:52 +0000541 public:
542 SwitchConvertDiagnoser(Expr *Cond)
543 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000544
Douglas Gregore2b37442012-05-04 22:38:52 +0000545 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
546 QualType T) {
547 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
548 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000549
Douglas Gregore2b37442012-05-04 22:38:52 +0000550 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
551 QualType T) {
552 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
553 << T << Cond->getSourceRange();
554 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000555
Douglas Gregore2b37442012-05-04 22:38:52 +0000556 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
557 QualType T,
558 QualType ConvTy) {
559 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
560 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000561
Douglas Gregore2b37442012-05-04 22:38:52 +0000562 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
563 QualType ConvTy) {
564 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
565 << ConvTy->isEnumeralType() << ConvTy;
566 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000567
Douglas Gregore2b37442012-05-04 22:38:52 +0000568 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
569 QualType T) {
570 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
571 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000572
Douglas Gregore2b37442012-05-04 22:38:52 +0000573 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
574 QualType ConvTy) {
575 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
576 << ConvTy->isEnumeralType() << ConvTy;
577 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000578
Douglas Gregore2b37442012-05-04 22:38:52 +0000579 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
580 QualType T,
581 QualType ConvTy) {
582 return DiagnosticBuilder::getEmpty();
583 }
584 } SwitchDiagnoser(Cond);
585
John McCallb268a282010-08-23 23:25:46 +0000586 CondResult
Douglas Gregore2b37442012-05-04 22:38:52 +0000587 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +0000588 /*AllowScopedEnumerations*/ true);
John McCallb268a282010-08-23 23:25:46 +0000589 if (CondResult.isInvalid()) return StmtError();
590 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
John McCall5939b162011-08-06 07:30:58 +0000592 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
593 CondResult = UsualUnaryConversions(Cond);
594 if (CondResult.isInvalid()) return StmtError();
595 Cond = CondResult.take();
596
John McCall48871652010-08-21 09:40:31 +0000597 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000598 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000599 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000600 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000601 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000602 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000603 }
John McCalla95172b2010-08-01 00:26:45 +0000604
John McCallaab3e412010-08-25 08:40:02 +0000605 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
John McCallb268a282010-08-23 23:25:46 +0000607 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000608 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000609 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000610}
611
Gabor Greif16e02862010-10-01 22:05:14 +0000612static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
613 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000614 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000615 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000616 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000617 Val.setIsSigned(IsSigned);
618}
619
John McCalldadc5752010-08-24 06:29:42 +0000620StmtResult
John McCallb268a282010-08-23 23:25:46 +0000621Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
622 Stmt *BodyStmt) {
623 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000624 assert(SS == getCurFunction()->SwitchStack.back() &&
625 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000626
Steve Naroff42a350a2007-09-01 21:08:38 +0000627 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000628 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000629
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000630 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000631 if (!CondExpr) return StmtError();
632
633 QualType CondType = CondExpr->getType();
634
John McCalld3dfbd62010-05-18 03:19:21 +0000635 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000636 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000637 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000638
Chris Lattnera96d4272009-10-16 16:45:22 +0000639 // C++ 6.4.2.p2:
640 // Integral promotions are performed (on the switch condition).
641 //
642 // A case value unrepresentable by the original switch condition
643 // type (before the promotion) doesn't make sense, even when it can
644 // be represented by the promoted type. Therefore we need to find
645 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000646 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000647 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000649 // appropriate type now, just return an error.
650 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000651 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000652
Chris Lattner4ebae652010-04-16 23:34:13 +0000653 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000654 // switch(bool_expr) {...} is often a programmer error, e.g.
655 // switch(n && mask) { ... } // Doh - should be "n & mask".
656 // One can always use an if statement instead of switch(bool_expr).
657 Diag(SwitchLoc, diag::warn_bool_switch_condition)
658 << CondExpr->getSourceRange();
659 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000660 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000661
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000662 // Get the bitwidth of the switched-on value before promotions. We must
663 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000664 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000665 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000666 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000667 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier02a84392012-08-10 17:56:09 +0000668 bool CondIsSigned
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000669 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000671 // Accumulate all of the case values in a vector so that we can sort them
672 // and detect duplicates. This vector contains the APInt for the case after
673 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000674 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000675 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000677 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000678 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
679 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000681 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattner10cb5e52007-08-23 06:23:56 +0000683 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000684
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000685 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000686 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000687
Anders Carlsson51873c22007-07-22 07:07:56 +0000688 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000689 if (TheDefaultStmt) {
690 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000691 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000692
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000693 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000694 // we'll return a valid AST. This requires recursing down the AST and
695 // finding it, not something we are set up to do right now. For now,
696 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000697 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000698 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000699 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000701 } else {
702 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattnera65e1f32008-01-16 19:17:22 +0000704 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000705
706 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
707 HasDependentValue = true;
708 break;
709 }
Mike Stump11289f42009-09-09 15:08:12 +0000710
Richard Smithf8379a02012-01-18 23:55:52 +0000711 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000712
David Blaikiebbafb8a2012-03-11 07:00:24 +0000713 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000714 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
715 // constant expression of the promoted type of the switch condition.
716 ExprResult ConvLo =
717 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
718 if (ConvLo.isInvalid()) {
719 CaseListIsErroneous = true;
720 continue;
721 }
722 Lo = ConvLo.take();
723 } else {
724 // We already verified that the expression has a i-c-e value (C99
725 // 6.8.4.2p3) - get that value now.
726 LoVal = Lo->EvaluateKnownConstInt(Context);
727
728 // If the LHS is not the same type as the condition, insert an implicit
729 // cast.
730 Lo = DefaultLvalueConversion(Lo).take();
731 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
732 }
733
734 // Convert the value to the same width/sign as the condition had prior to
735 // integral promotions.
736 //
737 // FIXME: This causes us to reject valid code:
738 // switch ((char)c) { case 256: case 0: return 0; }
739 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000740 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000741 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000742 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000743
Chris Lattnera65e1f32008-01-16 19:17:22 +0000744 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner10cb5e52007-08-23 06:23:56 +0000746 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000747 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000748 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000749 CS->getRHS()->isValueDependent()) {
750 HasDependentValue = true;
751 break;
752 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000753 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000754 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000755 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000756 }
757 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000758
759 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000760 // If we don't have a default statement, check whether the
761 // condition is constant.
762 llvm::APSInt ConstantCondValue;
763 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000764 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000765 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000766 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
767 Expr::SE_AllowSideEffects);
768 assert(!HasConstantCond ||
769 (ConstantCondValue.getBitWidth() == CondWidth &&
770 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000771 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000772 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000773
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000774 // Sort all the scalar case values so we can easily detect duplicates.
775 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
776
777 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000778 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
779 if (ShouldCheckConstantCond &&
780 CaseVals[i].first == ConstantCondValue)
781 ShouldCheckConstantCond = false;
782
783 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000784 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000785 // First, determine if either case value has a name
786 StringRef PrevString, CurrString;
787 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
788 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
789 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
790 PrevString = DeclRef->getDecl()->getName();
791 }
792 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
793 CurrString = DeclRef->getDecl()->getName();
794 }
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000795 llvm::SmallString<16> CaseValStr;
796 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000797
798 if (PrevString == CurrString)
799 Diag(CaseVals[i].second->getLHS()->getLocStart(),
800 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000801 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000802 else
803 Diag(CaseVals[i].second->getLHS()->getLocStart(),
804 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000805 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
806 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000807 CaseValStr;
808
John McCalld3dfbd62010-05-18 03:19:21 +0000809 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000810 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000811 // FIXME: We really want to remove the bogus case stmt from the
812 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000813 CaseListIsErroneous = true;
814 }
815 }
816 }
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000818 // Detect duplicate case ranges, which usually don't exist at all in
819 // the first place.
820 if (!CaseRanges.empty()) {
821 // Sort all the case ranges by their low value so we can easily detect
822 // overlaps between ranges.
823 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000825 // Scan the ranges, computing the high values and removing empty ranges.
826 std::vector<llvm::APSInt> HiVals;
827 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000828 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000829 CaseStmt *CR = CaseRanges[i].second;
830 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000831 llvm::APSInt HiVal;
832
David Blaikiebbafb8a2012-03-11 07:00:24 +0000833 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000834 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
835 // constant expression of the promoted type of the switch condition.
836 ExprResult ConvHi =
837 CheckConvertedConstantExpression(Hi, CondType, HiVal,
838 CCEK_CaseValue);
839 if (ConvHi.isInvalid()) {
840 CaseListIsErroneous = true;
841 continue;
842 }
843 Hi = ConvHi.take();
844 } else {
845 HiVal = Hi->EvaluateKnownConstInt(Context);
846
847 // If the RHS is not the same type as the condition, insert an
848 // implicit cast.
849 Hi = DefaultLvalueConversion(Hi).take();
850 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
851 }
Mike Stump11289f42009-09-09 15:08:12 +0000852
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000853 // Convert the value to the same width/sign as the condition.
854 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000855 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000856 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000857
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000858 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000860 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000861 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000862 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
863 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000864 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000865 CaseRanges.erase(CaseRanges.begin()+i);
866 --i, --e;
867 continue;
868 }
John McCalld3dfbd62010-05-18 03:19:21 +0000869
870 if (ShouldCheckConstantCond &&
871 LoVal <= ConstantCondValue &&
872 ConstantCondValue <= HiVal)
873 ShouldCheckConstantCond = false;
874
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000875 HiVals.push_back(HiVal);
876 }
Mike Stump11289f42009-09-09 15:08:12 +0000877
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000878 // Rescan the ranges, looking for overlap with singleton values and other
879 // ranges. Since the range list is sorted, we only need to compare case
880 // ranges with their neighbors.
881 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
882 llvm::APSInt &CRLo = CaseRanges[i].first;
883 llvm::APSInt &CRHi = HiVals[i];
884 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000886 // Check to see whether the case range overlaps with any
887 // singleton cases.
888 CaseStmt *OverlapStmt = 0;
889 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000890
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000891 // Find the smallest value >= the lower bound. If I is in the
892 // case range, then we have overlap.
893 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
894 CaseVals.end(), CRLo,
895 CaseCompareFunctor());
896 if (I != CaseVals.end() && I->first < CRHi) {
897 OverlapVal = I->first; // Found overlap with scalar.
898 OverlapStmt = I->second;
899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000901 // Find the smallest value bigger than the upper bound.
902 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
903 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
904 OverlapVal = (I-1)->first; // Found overlap with scalar.
905 OverlapStmt = (I-1)->second;
906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 // Check to see if this case stmt overlaps with the subsequent
909 // case range.
910 if (i && CRLo <= HiVals[i-1]) {
911 OverlapVal = HiVals[i-1]; // Found overlap with range.
912 OverlapStmt = CaseRanges[i-1].second;
913 }
Mike Stump11289f42009-09-09 15:08:12 +0000914
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000915 if (OverlapStmt) {
916 // If we have a duplicate, report it.
917 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
918 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000919 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000920 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000921 // FIXME: We really want to remove the bogus case stmt from the
922 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923 CaseListIsErroneous = true;
924 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000925 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000926 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000927
John McCalld3dfbd62010-05-18 03:19:21 +0000928 // Complain if we have a constant condition and we didn't find a match.
929 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
930 // TODO: it would be nice if we printed enums as enums, chars as
931 // chars, etc.
932 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
933 << ConstantCondValue.toString(10)
934 << CondExpr->getSourceRange();
935 }
936
937 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000938 // values. We only issue a warning if there is not 'default:', but
939 // we still do the analysis to preserve this information in the AST
940 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000941 //
Chris Lattner51679082010-09-16 17:09:42 +0000942 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000943
Douglas Gregorbd6839732010-02-08 22:24:16 +0000944 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000945 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000946 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000947 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000948 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000949 EnumValsTy EnumVals;
950
John McCalld3dfbd62010-05-18 03:19:21 +0000951 // Gather all enum values, set their type and sort them,
952 // allowing easier comparison with CaseVals.
953 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000954 EDI != ED->enumerator_end(); ++EDI) {
955 llvm::APSInt Val = EDI->getInitVal();
956 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie40ed2972012-06-06 20:45:41 +0000957 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000958 }
959 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000960 EnumValsTy::iterator EIend =
961 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000962
963 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +0000964 EnumValsTy::const_iterator EI = EnumVals.begin();
965 for (CaseValsTy::const_iterator CI = CaseVals.begin();
966 CI != CaseVals.end(); CI++) {
967 while (EI != EIend && EI->first < CI->first)
968 EI++;
969 if (EI == EIend || EI->first > CI->first)
970 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000971 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +0000972 }
973 // See which of case ranges aren't in enum
974 EI = EnumVals.begin();
975 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
976 RI != CaseRanges.end() && EI != EIend; RI++) {
977 while (EI != EIend && EI->first < RI->first)
978 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
David Blaikiee476f972012-01-22 02:31:55 +0000980 if (EI == EIend || EI->first != RI->first) {
981 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000982 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +0000983 }
David Blaikiee476f972012-01-22 02:31:55 +0000984
Chad Rosier02a84392012-08-10 17:56:09 +0000985 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +0000986 RI->second->getRHS()->EvaluateKnownConstInt(Context);
987 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
988 while (EI != EIend && EI->first < Hi)
989 EI++;
990 if (EI == EIend || EI->first != Hi)
991 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000992 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000994
Ted Kremenekc42f3452010-09-09 00:05:53 +0000995 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000996 CaseValsTy::const_iterator CI = CaseVals.begin();
997 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000998 bool hasCasesNotInSwitch = false;
999
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001000 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001
David Blaikiee476f972012-01-22 02:31:55 +00001002 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001003 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001004 llvm::APSInt CIVal;
1005 while (CI != CaseVals.end() && CI->first < EI->first)
1006 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregorbd6839732010-02-08 22:24:16 +00001008 if (CI != CaseVals.end() && CI->first == EI->first)
1009 continue;
1010
Ted Kremenekc42f3452010-09-09 00:05:53 +00001011 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001012 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001013 llvm::APSInt Hi =
1014 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001015 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001016 if (EI->first <= Hi)
1017 break;
1018 }
1019
Ted Kremenekc42f3452010-09-09 00:05:53 +00001020 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001021 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001022 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001023 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001025
David Blaikie60ac6382012-01-23 04:46:12 +00001026 if (TheDefaultStmt && UnhandledNames.empty())
1027 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001028
Chris Lattner51679082010-09-16 17:09:42 +00001029 // Produce a nice diagnostic if multiple values aren't handled.
1030 switch (UnhandledNames.size()) {
1031 case 0: break;
1032 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001033 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001034 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001035 << UnhandledNames[0];
1036 break;
1037 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001038 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001039 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001040 << UnhandledNames[0] << UnhandledNames[1];
1041 break;
1042 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001043 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1044 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001045 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1046 break;
1047 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001048 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1049 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001050 << (unsigned)UnhandledNames.size()
1051 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1052 break;
1053 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001054
1055 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001056 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001057 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001058 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001059
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001060 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1061 diag::warn_empty_switch_body);
1062
Mike Stump87c57ac2009-05-16 07:39:55 +00001063 // FIXME: If the case list was broken is some way, we don't have a good system
1064 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001065 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001066 return StmtError();
1067
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001068 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001069}
1070
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001071void
1072Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1073 Expr *SrcExpr) {
1074 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier02a84392012-08-10 17:56:09 +00001075 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001076 == DiagnosticsEngine::Ignored)
1077 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001078
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001079 if (const EnumType *ET = DstType->getAs<EnumType>())
1080 if (!Context.hasSameType(SrcType, DstType) &&
1081 SrcType->isIntegerType()) {
1082 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1083 SrcExpr->isIntegerConstantExpr(Context)) {
1084 // Get the bitwidth of the enum value before promotions.
1085 unsigned DstWith = Context.getIntWidth(DstType);
1086 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1087
1088 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1089 const EnumDecl *ED = ET->getDecl();
1090 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1091 EnumValsTy;
1092 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001093
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001094 // Gather all enum values, set their type and sort them,
1095 // allowing easier comparison with rhs constant.
1096 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1097 EDI != ED->enumerator_end(); ++EDI) {
1098 llvm::APSInt Val = EDI->getInitVal();
1099 AdjustAPSInt(Val, DstWith, DstIsSigned);
1100 EnumVals.push_back(std::make_pair(Val, *EDI));
1101 }
1102 if (EnumVals.empty())
1103 return;
1104 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1105 EnumValsTy::iterator EIend =
1106 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001107
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001108 // See which case values aren't in enum.
1109 EnumValsTy::const_iterator EI = EnumVals.begin();
1110 while (EI != EIend && EI->first < RhsVal)
1111 EI++;
1112 if (EI == EIend || EI->first != RhsVal) {
1113 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1114 << DstType;
1115 }
1116 }
1117 }
1118}
1119
John McCalldadc5752010-08-24 06:29:42 +00001120StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001121Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001122 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001123 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001124
Douglas Gregor680f8612009-11-24 21:15:44 +00001125 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001126 if (CondVar) {
1127 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001128 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001129 if (CondResult.isInvalid())
1130 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001131 }
John McCallb268a282010-08-23 23:25:46 +00001132 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001133 if (!ConditionExpr)
1134 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001135
John McCallb268a282010-08-23 23:25:46 +00001136 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001137
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001138 if (isa<NullStmt>(Body))
1139 getCurCompoundScope().setHasEmptyLoopBodies();
1140
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001141 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001142 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001143}
1144
John McCalldadc5752010-08-24 06:29:42 +00001145StmtResult
John McCallb268a282010-08-23 23:25:46 +00001146Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001147 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001148 Expr *Cond, SourceLocation CondRParen) {
1149 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001150
John Wiegley01296292011-04-08 18:41:53 +00001151 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001152 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001153 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001154 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001155
John McCallacf0ee52010-10-08 02:01:28 +00001156 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001157 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001158 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001159 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001160 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001161
John McCallb268a282010-08-23 23:25:46 +00001162 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001163
John McCallb268a282010-08-23 23:25:46 +00001164 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001165}
1166
Richard Trieu451a5db2012-04-30 18:01:30 +00001167namespace {
1168 // This visitor will traverse a conditional statement and store all
1169 // the evaluated decls into a vector. Simple is set to true if none
1170 // of the excluded constructs are used.
1171 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1172 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1173 llvm::SmallVector<SourceRange, 10> &Ranges;
1174 bool Simple;
Richard Trieu451a5db2012-04-30 18:01:30 +00001175public:
1176 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1177
1178 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001179 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu451a5db2012-04-30 18:01:30 +00001180 Inherited(S.Context),
1181 Decls(Decls),
1182 Ranges(Ranges),
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001183 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001184
1185 bool isSimple() { return Simple; }
1186
1187 // Replaces the method in EvaluatedExprVisitor.
1188 void VisitMemberExpr(MemberExpr* E) {
1189 Simple = false;
1190 }
1191
1192 // Any Stmt not whitelisted will cause the condition to be marked complex.
1193 void VisitStmt(Stmt *S) {
1194 Simple = false;
1195 }
1196
1197 void VisitBinaryOperator(BinaryOperator *E) {
1198 Visit(E->getLHS());
1199 Visit(E->getRHS());
1200 }
1201
1202 void VisitCastExpr(CastExpr *E) {
1203 Visit(E->getSubExpr());
1204 }
1205
1206 void VisitUnaryOperator(UnaryOperator *E) {
1207 // Skip checking conditionals with derefernces.
1208 if (E->getOpcode() == UO_Deref)
1209 Simple = false;
1210 else
1211 Visit(E->getSubExpr());
1212 }
1213
1214 void VisitConditionalOperator(ConditionalOperator *E) {
1215 Visit(E->getCond());
1216 Visit(E->getTrueExpr());
1217 Visit(E->getFalseExpr());
1218 }
1219
1220 void VisitParenExpr(ParenExpr *E) {
1221 Visit(E->getSubExpr());
1222 }
1223
1224 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1225 Visit(E->getOpaqueValue()->getSourceExpr());
1226 Visit(E->getFalseExpr());
1227 }
1228
1229 void VisitIntegerLiteral(IntegerLiteral *E) { }
1230 void VisitFloatingLiteral(FloatingLiteral *E) { }
1231 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1232 void VisitCharacterLiteral(CharacterLiteral *E) { }
1233 void VisitGNUNullExpr(GNUNullExpr *E) { }
1234 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1235
1236 void VisitDeclRefExpr(DeclRefExpr *E) {
1237 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1238 if (!VD) return;
1239
1240 Ranges.push_back(E->getSourceRange());
1241
1242 Decls.insert(VD);
1243 }
1244
1245 }; // end class DeclExtractor
1246
1247 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001248 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001249 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1250 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1251 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001252
1253public:
1254 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1255
1256 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1257 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1258 if (!Statement) return;
1259
1260 Visit(Statement);
1261 }
1262
1263 void VisitReturnStmt(ReturnStmt *S) {
1264 FoundDecl = true;
1265 }
1266
1267 void VisitBreakStmt(BreakStmt *S) {
1268 FoundDecl = true;
1269 }
1270
1271 void VisitGotoStmt(GotoStmt *S) {
1272 FoundDecl = true;
1273 }
1274
1275 void VisitCastExpr(CastExpr *E) {
1276 if (E->getCastKind() == CK_LValueToRValue)
1277 CheckLValueToRValueCast(E->getSubExpr());
1278 else
1279 Visit(E->getSubExpr());
1280 }
1281
1282 void CheckLValueToRValueCast(Expr *E) {
1283 E = E->IgnoreParenImpCasts();
1284
1285 if (isa<DeclRefExpr>(E)) {
1286 return;
1287 }
1288
1289 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1290 Visit(CO->getCond());
1291 CheckLValueToRValueCast(CO->getTrueExpr());
1292 CheckLValueToRValueCast(CO->getFalseExpr());
1293 return;
1294 }
1295
1296 if (BinaryConditionalOperator *BCO =
1297 dyn_cast<BinaryConditionalOperator>(E)) {
1298 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1299 CheckLValueToRValueCast(BCO->getFalseExpr());
1300 return;
1301 }
1302
1303 Visit(E);
1304 }
1305
1306 void VisitDeclRefExpr(DeclRefExpr *E) {
1307 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1308 if (Decls.count(VD))
1309 FoundDecl = true;
1310 }
1311
1312 bool FoundDeclInUse() { return FoundDecl; }
1313
1314 }; // end class DeclMatcher
1315
1316 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1317 Expr *Third, Stmt *Body) {
1318 // Condition is empty
1319 if (!Second) return;
1320
1321 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1322 Second->getLocStart())
1323 == DiagnosticsEngine::Ignored)
1324 return;
1325
1326 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1327 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1328 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001329 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001330 DE.Visit(Second);
1331
1332 // Don't analyze complex conditionals.
1333 if (!DE.isSimple()) return;
1334
1335 // No decls found.
1336 if (Decls.size() == 0) return;
1337
Richard Trieu0030f1d2012-05-04 03:01:54 +00001338 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001339 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1340 E = Decls.end();
1341 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001342 if ((*I)->getType().isVolatileQualified() ||
1343 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001344
1345 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1346 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1347 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1348 return;
1349
1350 // Load decl names into diagnostic.
1351 if (Decls.size() > 4)
1352 PDiag << 0;
1353 else {
1354 PDiag << Decls.size();
1355 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1356 E = Decls.end();
1357 I != E; ++I)
1358 PDiag << (*I)->getDeclName();
1359 }
1360
1361 // Load SourceRanges into diagnostic if there is room.
1362 // Otherwise, load the SourceRange of the conditional expression.
1363 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1364 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1365 E = Ranges.end();
1366 I != E; ++I)
1367 PDiag << *I;
1368 else
1369 PDiag << Second->getSourceRange();
1370
1371 S.Diag(Ranges.begin()->getBegin(), PDiag);
1372 }
1373
1374} // end namespace
1375
John McCalldadc5752010-08-24 06:29:42 +00001376StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001377Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001378 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001379 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001380 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001381 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001382 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001383 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1384 // declare identifiers for objects having storage class 'auto' or
1385 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001386 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1387 DI!=DE; ++DI) {
1388 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001389 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001390 VD = 0;
1391 if (VD == 0)
1392 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1393 // FIXME: mark decl erroneous!
1394 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001395 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001396 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001397
Richard Trieu451a5db2012-04-30 18:01:30 +00001398 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1399
John McCalldadc5752010-08-24 06:29:42 +00001400 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001401 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001402 if (secondVar) {
1403 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001404 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001405 if (SecondResult.isInvalid())
1406 return StmtError();
1407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001408
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001409 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
Anders Carlsson1682af52009-08-01 01:39:59 +00001411 DiagnoseUnusedExprResult(First);
1412 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001413 DiagnoseUnusedExprResult(Body);
1414
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001415 if (isa<NullStmt>(Body))
1416 getCurCompoundScope().setHasEmptyLoopBodies();
1417
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 return Owned(new (Context) ForStmt(Context, First,
1419 SecondResult.take(), ConditionVar,
1420 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001421 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001422}
1423
John McCall34376a62010-12-04 03:47:34 +00001424/// In an Objective C collection iteration statement:
1425/// for (x in y)
1426/// x can be an arbitrary l-value expression. Bind it up as a
1427/// full-expression.
1428StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001429 // Reduce placeholder expressions here. Note that this rejects the
1430 // use of pseudo-object l-values in this position.
1431 ExprResult result = CheckPlaceholderExpr(E);
1432 if (result.isInvalid()) return StmtError();
1433 E = result.take();
1434
John McCall34376a62010-12-04 03:47:34 +00001435 CheckImplicitConversions(E);
John McCallbc153352012-03-30 05:43:39 +00001436
1437 result = MaybeCreateExprWithCleanups(E);
1438 if (result.isInvalid()) return StmtError();
1439
1440 return Owned(static_cast<Stmt*>(result.take()));
John McCall34376a62010-12-04 03:47:34 +00001441}
1442
John McCall53848232011-07-27 01:07:15 +00001443ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001444Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1445 if (!collection)
1446 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001447
John McCall53848232011-07-27 01:07:15 +00001448 // Bail out early if we've got a type-dependent expression.
1449 if (collection->isTypeDependent()) return Owned(collection);
1450
1451 // Perform normal l-value conversion.
1452 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1453 if (result.isInvalid())
1454 return ExprError();
1455 collection = result.take();
1456
1457 // The operand needs to have object-pointer type.
1458 // TODO: should we do a contextual conversion?
1459 const ObjCObjectPointerType *pointerType =
1460 collection->getType()->getAs<ObjCObjectPointerType>();
1461 if (!pointerType)
1462 return Diag(forLoc, diag::err_collection_expr_type)
1463 << collection->getType() << collection->getSourceRange();
1464
1465 // Check that the operand provides
1466 // - countByEnumeratingWithState:objects:count:
1467 const ObjCObjectType *objectType = pointerType->getObjectType();
1468 ObjCInterfaceDecl *iface = objectType->getInterface();
1469
1470 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001471 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001472 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001473 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001474 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001475 ? diag::err_arc_collection_forward
1476 : 0,
1477 collection)) {
John McCall53848232011-07-27 01:07:15 +00001478 // Otherwise, if we have any useful type information, check that
1479 // the type declares the appropriate method.
1480 } else if (iface || !objectType->qual_empty()) {
1481 IdentifierInfo *selectorIdents[] = {
1482 &Context.Idents.get("countByEnumeratingWithState"),
1483 &Context.Idents.get("objects"),
1484 &Context.Idents.get("count")
1485 };
1486 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1487
1488 ObjCMethodDecl *method = 0;
1489
1490 // If there's an interface, look in both the public and private APIs.
1491 if (iface) {
1492 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001493 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001494 }
1495
1496 // Also check protocol qualifiers.
1497 if (!method)
1498 method = LookupMethodInQualifiedType(selector, pointerType,
1499 /*instance*/ true);
1500
1501 // If we didn't find it anywhere, give up.
1502 if (!method) {
1503 Diag(forLoc, diag::warn_collection_expr_type)
1504 << collection->getType() << selector << collection->getSourceRange();
1505 }
1506
1507 // TODO: check for an incompatible signature?
1508 }
1509
1510 // Wrap up any cleanups in the expression.
1511 return Owned(MaybeCreateExprWithCleanups(collection));
1512}
1513
John McCalldadc5752010-08-24 06:29:42 +00001514StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001515Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001516 Stmt *First, Expr *collection,
1517 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001518
1519 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001520 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001521
Fariborz Jahanian93977672008-01-10 20:33:58 +00001522 if (First) {
1523 QualType FirstType;
1524 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001525 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001526 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1527 diag::err_toomany_element_decls));
1528
John McCall31168b02011-06-15 23:02:42 +00001529 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1530 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001531 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1532 // declare identifiers for objects having storage class 'auto' or
1533 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001534 if (!D->hasLocalStorage())
1535 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001536 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001537 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001538 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001539 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001540 return StmtError(Diag(First->getLocStart(),
1541 diag::err_selector_element_not_lvalue)
1542 << First->getSourceRange());
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001545 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001546 if (!FirstType->isDependentType() &&
1547 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001548 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001549 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1550 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001551 }
Chad Rosier02a84392012-08-10 17:56:09 +00001552
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001553 if (CollectionExprResult.isInvalid())
1554 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001555
1556 return Owned(new (Context) ObjCForCollectionStmt(First,
1557 CollectionExprResult.take(), 0,
Ted Kremenek5a201952009-02-07 01:47:29 +00001558 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001559}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001560
Richard Smith02e85f32011-04-14 22:09:26 +00001561/// Finish building a variable declaration for a for-range statement.
1562/// \return true if an error occurs.
1563static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1564 SourceLocation Loc, int diag) {
1565 // Deduce the type for the iterator variable now rather than leaving it to
1566 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1567 TypeSourceInfo *InitTSI = 0;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001568 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redl09edce02012-01-23 22:09:39 +00001569 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1570 Sema::DAR_Failed)
Richard Smith02e85f32011-04-14 22:09:26 +00001571 SemaRef.Diag(Loc, diag) << Init->getType();
1572 if (!InitTSI) {
1573 Decl->setInvalidDecl();
1574 return true;
1575 }
1576 Decl->setTypeSourceInfo(InitTSI);
1577 Decl->setType(InitTSI->getType());
1578
John McCall31168b02011-06-15 23:02:42 +00001579 // In ARC, infer lifetime.
1580 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1581 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001582 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001583 SemaRef.inferObjCARCLifetime(Decl))
1584 Decl->setInvalidDecl();
1585
Richard Smith02e85f32011-04-14 22:09:26 +00001586 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1587 /*TypeMayContainAuto=*/false);
1588 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001589 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001590 return false;
1591}
1592
Sam Panzer0f384432012-08-21 00:52:01 +00001593namespace {
1594
Richard Smith02e85f32011-04-14 22:09:26 +00001595/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001596/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001597/// nor from the diagnostics produced when analysing the implicit expressions
1598/// required in a for-range statement.
1599void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001600 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001601 CallExpr *CE = dyn_cast<CallExpr>(E);
1602 if (!CE)
1603 return;
1604 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1605 if (!D)
1606 return;
1607 SourceLocation Loc = D->getLocation();
1608
1609 std::string Description;
1610 bool IsTemplate = false;
1611 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1612 Description = SemaRef.getTemplateArgumentBindingsText(
1613 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1614 IsTemplate = true;
1615 }
1616
1617 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1618 << BEF << IsTemplate << Description << E->getType();
1619}
1620
Sam Panzer0f384432012-08-21 00:52:01 +00001621/// Build a variable declaration for a for-range statement.
1622VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1623 QualType Type, const char *Name) {
1624 DeclContext *DC = SemaRef.CurContext;
1625 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1626 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1627 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1628 TInfo, SC_Auto, SC_None);
1629 Decl->setImplicit();
1630 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001631}
1632
1633}
1634
Fariborz Jahanian00213472012-07-06 19:04:04 +00001635static bool ObjCEnumerationCollection(Expr *Collection) {
1636 return !Collection->isTypeDependent()
1637 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1638}
1639
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001640/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001641///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001642/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001643/// A range-based for statement is equivalent to
1644///
1645/// {
1646/// auto && __range = range-init;
1647/// for ( auto __begin = begin-expr,
1648/// __end = end-expr;
1649/// __begin != __end;
1650/// ++__begin ) {
1651/// for-range-declaration = *__begin;
1652/// statement
1653/// }
1654/// }
1655///
1656/// The body of the loop is not available yet, since it cannot be analysed until
1657/// we have determined the type of the for-range-declaration.
1658StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001659Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001660 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001661 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00001662 if (!First || !Range)
1663 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001664
Fariborz Jahanian00213472012-07-06 19:04:04 +00001665 if (ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001666 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001667
1668 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1669 assert(DS && "first part of for range not a decl stmt");
1670
1671 if (!DS->isSingleDecl()) {
1672 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1673 return StmtError();
1674 }
1675 if (DS->getSingleDecl()->isInvalidDecl())
1676 return StmtError();
1677
1678 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1679 return StmtError();
1680
1681 // Build auto && __range = range-init
1682 SourceLocation RangeLoc = Range->getLocStart();
1683 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1684 Context.getAutoRRefDeductType(),
1685 "__range");
1686 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1687 diag::err_for_range_deduction_failure))
1688 return StmtError();
1689
1690 // Claim the type doesn't contain auto: we've already done the checking.
1691 DeclGroupPtrTy RangeGroup =
1692 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1693 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1694 if (RangeDecl.isInvalid())
1695 return StmtError();
1696
1697 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1698 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
Richard Smitha05b3b52012-09-20 21:52:32 +00001699 RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001700}
1701
1702/// \brief Create the initialization, compare, and increment steps for
1703/// the range-based for loop expression.
1704/// This function does not handle array-based for loops,
1705/// which are created in Sema::BuildCXXForRangeStmt.
1706///
1707/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1708/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1709/// CandidateSet and BEF are set and some non-success value is returned on
1710/// failure.
1711static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1712 Expr *BeginRange, Expr *EndRange,
1713 QualType RangeType,
1714 VarDecl *BeginVar,
1715 VarDecl *EndVar,
1716 SourceLocation ColonLoc,
1717 OverloadCandidateSet *CandidateSet,
1718 ExprResult *BeginExpr,
1719 ExprResult *EndExpr,
1720 Sema::BeginEndFunction *BEF) {
1721 DeclarationNameInfo BeginNameInfo(
1722 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1723 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1724 ColonLoc);
1725
1726 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1727 Sema::LookupMemberName);
1728 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1729
1730 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1731 // - if _RangeT is a class type, the unqualified-ids begin and end are
1732 // looked up in the scope of class _RangeT as if by class member access
1733 // lookup (3.4.5), and if either (or both) finds at least one
1734 // declaration, begin-expr and end-expr are __range.begin() and
1735 // __range.end(), respectively;
1736 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1737 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1738
1739 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1740 SourceLocation RangeLoc = BeginVar->getLocation();
1741 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1742
1743 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1744 << RangeLoc << BeginRange->getType() << *BEF;
1745 return Sema::FRS_DiagnosticIssued;
1746 }
1747 } else {
1748 // - otherwise, begin-expr and end-expr are begin(__range) and
1749 // end(__range), respectively, where begin and end are looked up with
1750 // argument-dependent lookup (3.4.2). For the purposes of this name
1751 // lookup, namespace std is an associated namespace.
1752
1753 }
1754
1755 *BEF = Sema::BEF_begin;
1756 Sema::ForRangeStatus RangeStatus =
1757 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1758 Sema::BEF_begin, BeginNameInfo,
1759 BeginMemberLookup, CandidateSet,
1760 BeginRange, BeginExpr);
1761
1762 if (RangeStatus != Sema::FRS_Success)
1763 return RangeStatus;
1764 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1765 diag::err_for_range_iter_deduction_failure)) {
1766 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1767 return Sema::FRS_DiagnosticIssued;
1768 }
1769
1770 *BEF = Sema::BEF_end;
1771 RangeStatus =
1772 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1773 Sema::BEF_end, EndNameInfo,
1774 EndMemberLookup, CandidateSet,
1775 EndRange, EndExpr);
1776 if (RangeStatus != Sema::FRS_Success)
1777 return RangeStatus;
1778 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1779 diag::err_for_range_iter_deduction_failure)) {
1780 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1781 return Sema::FRS_DiagnosticIssued;
1782 }
1783 return Sema::FRS_Success;
1784}
1785
1786/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00001787/// If the attempt fails, this function will return a valid, null StmtResult
1788/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00001789static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1790 SourceLocation ForLoc,
1791 Stmt *LoopVarDecl,
1792 SourceLocation ColonLoc,
1793 Expr *Range,
1794 SourceLocation RangeLoc,
1795 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00001796 // Determine whether we can rebuild the for-range statement with a
1797 // dereferenced range expression.
1798 ExprResult AdjustedRange;
1799 {
1800 Sema::SFINAETrap Trap(SemaRef);
1801
1802 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1803 if (AdjustedRange.isInvalid())
1804 return StmtResult();
1805
1806 StmtResult SR =
1807 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1808 AdjustedRange.get(), RParenLoc,
1809 Sema::BFRK_Check);
1810 if (SR.isInvalid())
1811 return StmtResult();
1812 }
1813
1814 // The attempt to dereference worked well enough that it could produce a valid
1815 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1816 // case there are any other (non-fatal) problems with it.
1817 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1818 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1819 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1820 AdjustedRange.get(), RParenLoc,
1821 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00001822}
1823
Richard Smitha05b3b52012-09-20 21:52:32 +00001824/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001825StmtResult
1826Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1827 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1828 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00001829 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00001830 Scope *S = getCurScope();
1831
1832 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1833 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1834 QualType RangeVarType = RangeVar->getType();
1835
1836 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1837 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1838
1839 StmtResult BeginEndDecl = BeginEnd;
1840 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1841
1842 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1843 SourceLocation RangeLoc = RangeVar->getLocation();
1844
Ted Kremenekbed648e2011-10-10 22:36:28 +00001845 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1846
1847 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1848 VK_LValue, ColonLoc);
1849 if (BeginRangeRef.isInvalid())
1850 return StmtError();
1851
1852 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1853 VK_LValue, ColonLoc);
1854 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00001855 return StmtError();
1856
1857 QualType AutoType = Context.getAutoDeductType();
1858 Expr *Range = RangeVar->getInit();
1859 if (!Range)
1860 return StmtError();
1861 QualType RangeType = Range->getType();
1862
1863 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001864 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00001865 return StmtError();
1866
1867 // Build auto __begin = begin-expr, __end = end-expr.
1868 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1869 "__begin");
1870 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1871 "__end");
1872
1873 // Build begin-expr and end-expr and attach to __begin and __end variables.
1874 ExprResult BeginExpr, EndExpr;
1875 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1876 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1877 // __range + __bound, respectively, where __bound is the array bound. If
1878 // _RangeT is an array of unknown size or an array of incomplete type,
1879 // the program is ill-formed;
1880
1881 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001882 BeginExpr = BeginRangeRef;
1883 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001884 diag::err_for_range_iter_deduction_failure)) {
1885 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1886 return StmtError();
1887 }
1888
1889 // Find the array bound.
1890 ExprResult BoundExpr;
1891 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1892 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001893 Context.getPointerDiffType(),
1894 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001895 else if (const VariableArrayType *VAT =
1896 dyn_cast<VariableArrayType>(UnqAT))
1897 BoundExpr = VAT->getSizeExpr();
1898 else {
1899 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1900 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00001901 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00001902 }
1903
1904 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001905 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00001906 BoundExpr.get());
1907 if (EndExpr.isInvalid())
1908 return StmtError();
1909 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1910 diag::err_for_range_iter_deduction_failure)) {
1911 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1912 return StmtError();
1913 }
1914 } else {
Sam Panzer0f384432012-08-21 00:52:01 +00001915 OverloadCandidateSet CandidateSet(RangeLoc);
1916 Sema::BeginEndFunction BEFFailure;
1917 ForRangeStatus RangeStatus =
1918 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1919 EndRangeRef.get(), RangeType,
1920 BeginVar, EndVar, ColonLoc, &CandidateSet,
1921 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00001922
Sam Panzer0f384432012-08-21 00:52:01 +00001923 // If building the range failed, try dereferencing the range expression
1924 // unless a diagnostic was issued or the end function is problematic.
Richard Smitha05b3b52012-09-20 21:52:32 +00001925 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00001926 BEFFailure == BEF_begin) {
1927 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1928 LoopVarDecl, ColonLoc,
1929 Range, RangeLoc,
1930 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00001931 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00001932 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00001933 }
1934
Sam Panzer0f384432012-08-21 00:52:01 +00001935 // Otherwise, emit diagnostics if we haven't already.
1936 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00001937 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00001938 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1939 << RangeLoc << Range->getType() << BEFFailure;
1940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
1941 llvm::makeArrayRef(&Range, /*NumArgs=*/1));
1942 }
1943 // Return an error if no fix was discovered.
1944 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00001945 return StmtError();
1946 }
1947
Sam Panzer0f384432012-08-21 00:52:01 +00001948 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1949 "invalid range expression in for loop");
1950
1951 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00001952 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1953 if (!Context.hasSameType(BeginType, EndType)) {
1954 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1955 << BeginType << EndType;
1956 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1957 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1958 }
1959
1960 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1961 // Claim the type doesn't contain auto: we've already done the checking.
1962 DeclGroupPtrTy BeginEndGroup =
1963 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1964 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1965
Ted Kremenekbed648e2011-10-10 22:36:28 +00001966 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1967 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00001968 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001969 if (BeginRef.isInvalid())
1970 return StmtError();
1971
Richard Smith02e85f32011-04-14 22:09:26 +00001972 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1973 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001974 if (EndRef.isInvalid())
1975 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00001976
1977 // Build and check __begin != __end expression.
1978 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1979 BeginRef.get(), EndRef.get());
1980 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1981 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1982 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00001983 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1984 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00001985 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1986 if (!Context.hasSameType(BeginType, EndType))
1987 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1988 return StmtError();
1989 }
1990
1991 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001992 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1993 VK_LValue, ColonLoc);
1994 if (BeginRef.isInvalid())
1995 return StmtError();
1996
Richard Smith02e85f32011-04-14 22:09:26 +00001997 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1998 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1999 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002000 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2001 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002002 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2003 return StmtError();
2004 }
2005
2006 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002007 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2008 VK_LValue, ColonLoc);
2009 if (BeginRef.isInvalid())
2010 return StmtError();
2011
Richard Smith02e85f32011-04-14 22:09:26 +00002012 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2013 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002014 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2015 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002016 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2017 return StmtError();
2018 }
2019
Richard Smitha05b3b52012-09-20 21:52:32 +00002020 // Attach *__begin as initializer for VD. Don't touch it if we're just
2021 // trying to determine whether this would be a valid range.
2022 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002023 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2024 /*TypeMayContainAuto=*/true);
2025 if (LoopVar->isInvalidDecl())
2026 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2027 }
Richard Smithf9603352011-06-21 23:07:19 +00002028 } else {
2029 // The range is implicitly used as a placeholder when it is dependent.
2030 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00002031 }
2032
Richard Smitha05b3b52012-09-20 21:52:32 +00002033 // Don't bother to actually allocate the result if we're just trying to
2034 // determine whether it would be valid.
2035 if (Kind == BFRK_Check)
2036 return StmtResult();
2037
Richard Smith02e85f32011-04-14 22:09:26 +00002038 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2039 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2040 NotEqExpr.take(), IncrExpr.take(),
2041 LoopVarDS, /*Body=*/0, ForLoc,
2042 ColonLoc, RParenLoc));
2043}
2044
Chad Rosier02a84392012-08-10 17:56:09 +00002045/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002046/// statement.
2047StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2048 if (!S || !B)
2049 return StmtError();
2050 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002051
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002052 ForStmt->setBody(B);
2053 return S;
2054}
2055
Richard Smith02e85f32011-04-14 22:09:26 +00002056/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2057/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2058/// body cannot be performed until after the type of the range variable is
2059/// determined.
2060StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2061 if (!S || !B)
2062 return StmtError();
2063
Fariborz Jahanian00213472012-07-06 19:04:04 +00002064 if (isa<ObjCForCollectionStmt>(S))
2065 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002066
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002067 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2068 ForStmt->setBody(B);
2069
2070 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2071 diag::warn_empty_range_based_for_body);
2072
Richard Smith02e85f32011-04-14 22:09:26 +00002073 return S;
2074}
2075
Chris Lattnercab02a62011-02-17 20:34:02 +00002076StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2077 SourceLocation LabelLoc,
2078 LabelDecl *TheDecl) {
2079 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002080 TheDecl->setUsed();
2081 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002082}
Chris Lattner1c310502007-05-31 06:00:00 +00002083
John McCalldadc5752010-08-24 06:29:42 +00002084StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002085Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002086 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002087 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002088 if (!E->isTypeDependent()) {
2089 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002090 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00002091 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00002092 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002093 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2094 if (ExprRes.isInvalid())
2095 return StmtError();
2096 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00002097 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002098 return StmtError();
Eli Friedman9ccdb1d2012-01-31 22:47:07 +00002099 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00002100 }
John McCalla95172b2010-08-01 00:26:45 +00002101
John McCallaab3e412010-08-25 08:40:02 +00002102 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002103
Douglas Gregor30776d42009-05-16 00:20:29 +00002104 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002105}
2106
John McCalldadc5752010-08-24 06:29:42 +00002107StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002108Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002109 Scope *S = CurScope->getContinueParent();
2110 if (!S) {
2111 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002112 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002113 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002114
Ted Kremenek5a201952009-02-07 01:47:29 +00002115 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002116}
2117
John McCalldadc5752010-08-24 06:29:42 +00002118StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002119Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002120 Scope *S = CurScope->getBreakParent();
2121 if (!S) {
2122 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002123 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002124 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002125
Ted Kremenek5a201952009-02-07 01:47:29 +00002126 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002127}
2128
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002130/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002131///
Douglas Gregor5d369002011-01-21 18:05:27 +00002132/// \param ReturnType If we're determining the copy elision candidate for
2133/// a return statement, this is the return type of the function. If we're
2134/// determining the copy elision candidate for a throw expression, this will
2135/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002136///
Douglas Gregor5d369002011-01-21 18:05:27 +00002137/// \param E The expression being returned from the function or block, or
2138/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002139///
Douglas Gregor86394412011-05-20 15:00:53 +00002140/// \param AllowFunctionParameter Whether we allow function parameters to
2141/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2142/// we re-use this logic to determine whether we should try to move as part of
2143/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002144///
2145/// \returns The NRVO candidate variable, if the return statement may use the
2146/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00002147const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2148 Expr *E,
2149 bool AllowFunctionParameter) {
2150 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002151 // - in a return statement in a function with ...
2152 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00002153 if (!ReturnType.isNull()) {
2154 if (!ReturnType->isRecordType())
2155 return 0;
2156 // ... the same cv-unqualified type as the function return type ...
2157 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2158 return 0;
2159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002160
2161 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00002162 // (other than a function or catch-clause parameter)) ...
2163 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber13253842012-07-11 22:50:15 +00002164 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002165 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002166 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2167 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002168 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
John McCall03318c12011-11-11 03:57:31 +00002170 // ...object (other than a function or catch-clause parameter)...
2171 if (VD->getKind() != Decl::Var &&
2172 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2173 return 0;
2174 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
John McCall03318c12011-11-11 03:57:31 +00002176 // ...automatic...
2177 if (!VD->hasLocalStorage()) return 0;
2178
2179 // ...non-volatile...
2180 if (VD->getType().isVolatileQualified()) return 0;
2181 if (VD->getType()->isReferenceType()) return 0;
2182
2183 // __block variables can't be allocated in a way that permits NRVO.
2184 if (VD->hasAttr<BlocksAttr>()) return 0;
2185
2186 // Variables with higher required alignment than their type's ABI
2187 // alignment cannot use NRVO.
2188 if (VD->hasAttr<AlignedAttr>() &&
2189 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2190 return 0;
2191
2192 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002193}
2194
Douglas Gregor626fbed2011-01-21 21:08:57 +00002195/// \brief Perform the initialization of a potentially-movable value, which
2196/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002197///
2198/// This routine implements C++0x [class.copy]p33, which attempts to treat
2199/// returned lvalues as rvalues in certain cases (to prefer move construction),
2200/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002202Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2203 const VarDecl *NRVOCandidate,
2204 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002205 Expr *Value,
2206 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002207 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208 // When the criteria for elision of a copy operation are met or would
2209 // be met save for the fact that the source object is a function
2210 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002211 // overload resolution to select the constructor for the copy is first
2212 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002213 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002214 if (AllowNRVO &&
2215 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002217 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002218
Douglas Gregorf282a762011-01-21 19:38:21 +00002219 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002221 = InitializationKind::CreateCopy(Value->getLocStart(),
2222 Value->getLocStart());
2223 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002224
2225 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002226 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002227 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002228 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002229 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002230 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2231 StepEnd = Seq.step_end();
2232 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002233 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002234 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002235
2236 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002237 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002238
Douglas Gregorf282a762011-01-21 19:38:21 +00002239 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002240 = Constructor->getParamDecl(0)->getType()
2241 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Douglas Gregorf282a762011-01-21 19:38:21 +00002243 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002245 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2246 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002247 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002248
Douglas Gregorf282a762011-01-21 19:38:21 +00002249 // Promote "AsRvalue" to the heap, since we now need this
2250 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002251 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002252 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002253
Douglas Gregorf282a762011-01-21 19:38:21 +00002254 // Complete type-checking the initialization of the return type
2255 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002256 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00002257 }
2258 }
2259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002260
Douglas Gregorf282a762011-01-21 19:38:21 +00002261 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002263 // (again) now with the return value expression as written.
2264 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002265 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002266
Douglas Gregorf282a762011-01-21 19:38:21 +00002267 return Res;
2268}
2269
Eli Friedman34b49062012-01-26 03:00:14 +00002270/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2271/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002272///
John McCalldadc5752010-08-24 06:29:42 +00002273StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002274Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2275 // If this is the first return we've seen, infer the return type.
2276 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2277 // rules which allows multiple return statements.
2278 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002279 QualType FnRetType = CurCap->ReturnType;
2280
2281 // For blocks/lambdas with implicit return types, we check each return
2282 // statement individually, and deduce the common return type when the block
2283 // or lambda is completed.
Eli Friedman34b49062012-01-26 03:00:14 +00002284 if (CurCap->HasImplicitReturnType) {
Douglas Gregor940a5502012-02-09 18:40:39 +00002285 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002286 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2287 if (Result.isInvalid())
2288 return StmtError();
2289 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002290
Jordan Rosed39e5f12012-07-02 21:19:23 +00002291 if (!RetValExp->isTypeDependent())
2292 FnRetType = RetValExp->getType();
2293 else
2294 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002295 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002296 if (RetValExp) {
2297 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2298 // initializer list, because it is not an expression (even
2299 // though we represent it as one). We still deduce 'void'.
2300 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2301 << RetValExp->getSourceRange();
2302 }
2303
Jordan Rosed39e5f12012-07-02 21:19:23 +00002304 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002305 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002306
2307 // Although we'll properly infer the type of the block once it's completed,
2308 // make sure we provide a return type now for better error recovery.
2309 if (CurCap->ReturnType.isNull())
2310 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002311 }
Eli Friedman34b49062012-01-26 03:00:14 +00002312 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002313
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002314 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002315 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2316 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2317 return StmtError();
2318 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002319 } else {
2320 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2321 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2322 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2323 return StmtError();
2324 }
2325 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002326
Steve Naroffc540d662008-09-03 18:15:37 +00002327 // Otherwise, verify that this result type matches the previous one. We are
2328 // pickier with blocks than for normal functions because we don't have GCC
2329 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002330 const VarDecl *NRVOCandidate = 0;
John McCall5500ef22011-08-17 22:09:46 +00002331 if (FnRetType->isDependentType()) {
2332 // Delay processing for now. TODO: there are lots of dependent
2333 // types we can conclusively prove aren't void.
2334 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002335 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002336 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002337 (RetValExp->isTypeDependent() ||
2338 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002339 if (!getLangOpts().CPlusPlus &&
2340 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002341 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002342 else {
2343 Diag(ReturnLoc, diag::err_return_block_has_expr);
2344 RetValExp = 0;
2345 }
Steve Naroffc540d662008-09-03 18:15:37 +00002346 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002347 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002348 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2349 } else if (!RetValExp->isTypeDependent()) {
2350 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002351
John McCall5500ef22011-08-17 22:09:46 +00002352 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2353 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2354 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002355
John McCall5500ef22011-08-17 22:09:46 +00002356 // In C++ the return statement is handled via a copy initialization.
2357 // the C version of which boils down to CheckSingleAssignmentConstraints.
2358 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2359 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2360 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002361 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002362 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2363 FnRetType, RetValExp);
2364 if (Res.isInvalid()) {
2365 // FIXME: Cleanup temporaries here, anyway?
2366 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002367 }
John McCall5500ef22011-08-17 22:09:46 +00002368 RetValExp = Res.take();
2369 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002370 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002371
John McCall75f92b52011-08-17 21:34:14 +00002372 if (RetValExp) {
2373 CheckImplicitConversions(RetValExp, ReturnLoc);
2374 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2375 }
John McCall5500ef22011-08-17 22:09:46 +00002376 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2377 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002378
Jordan Rosed39e5f12012-07-02 21:19:23 +00002379 // If we need to check for the named return value optimization,
2380 // or if we need to infer the return type,
2381 // save the return statement in our scope for later processing.
2382 if (CurCap->HasImplicitReturnType ||
2383 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2384 !CurContext->isDependentContext()))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002385 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002387 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002388}
Chris Lattneraf8d5812006-11-10 05:07:45 +00002389
John McCalldadc5752010-08-24 06:29:42 +00002390StmtResult
John McCallb268a282010-08-23 23:25:46 +00002391Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002392 // Check for unexpanded parameter packs.
2393 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2394 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002395
Eli Friedman34b49062012-01-26 03:00:14 +00002396 if (isa<CapturingScopeInfo>(getCurFunction()))
2397 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00002398
Chris Lattner79413952008-12-04 23:50:19 +00002399 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002400 QualType RelatedRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002401 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00002402 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00002403 if (FD->hasAttr<NoReturnAttr>() ||
2404 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00002405 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002406 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002407 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman410fc7a2012-03-30 01:13:43 +00002408 FnRetType = MD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00002409 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2410 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002411 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002412 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002413 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2414 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002415 }
2416 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002417 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002418
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002419 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002420 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002421 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002422 if (isa<InitListExpr>(RetValExp)) {
2423 // We simply never allow init lists as the return value of void
2424 // functions. This is compatible because this was never allowed before,
2425 // so there's no legacy code to deal with.
2426 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2427 int FunctionKind = 0;
2428 if (isa<ObjCMethodDecl>(CurDecl))
2429 FunctionKind = 1;
2430 else if (isa<CXXConstructorDecl>(CurDecl))
2431 FunctionKind = 2;
2432 else if (isa<CXXDestructorDecl>(CurDecl))
2433 FunctionKind = 3;
2434
2435 Diag(ReturnLoc, diag::err_return_init_list)
2436 << CurDecl->getDeclName() << FunctionKind
2437 << RetValExp->getSourceRange();
2438
2439 // Drop the expression.
2440 RetValExp = 0;
2441 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002442 // C99 6.8.6.4p1 (ext_ since GCC warns)
2443 unsigned D = diag::ext_return_has_expr;
2444 if (RetValExp->getType()->isVoidType())
2445 D = diag::ext_return_has_void_expr;
2446 else {
2447 ExprResult Result = Owned(RetValExp);
2448 Result = IgnoredValueConversions(Result.take());
2449 if (Result.isInvalid())
2450 return StmtError();
2451 RetValExp = Result.take();
2452 RetValExp = ImpCastExprToType(RetValExp,
2453 Context.VoidTy, CK_ToVoid).take();
2454 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002455
Nick Lewycky1be750a2011-06-01 07:44:31 +00002456 // return (some void expression); is legal in C++.
2457 if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002458 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002459 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002460
2461 int FunctionKind = 0;
2462 if (isa<ObjCMethodDecl>(CurDecl))
2463 FunctionKind = 1;
2464 else if (isa<CXXConstructorDecl>(CurDecl))
2465 FunctionKind = 2;
2466 else if (isa<CXXDestructorDecl>(CurDecl))
2467 FunctionKind = 3;
2468
Nick Lewycky1be750a2011-06-01 07:44:31 +00002469 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002470 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002471 << RetValExp->getSourceRange();
2472 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002473 }
Mike Stump11289f42009-09-09 15:08:12 +00002474
Sebastian Redleef474c2012-02-22 10:50:08 +00002475 if (RetValExp) {
2476 CheckImplicitConversions(RetValExp, ReturnLoc);
2477 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2478 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002481 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2482 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002483 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2484 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002485 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002486
2487 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002488 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002489 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002490 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002491 Result = new (Context) ReturnStmt(ReturnLoc);
2492 } else {
2493 const VarDecl *NRVOCandidate = 0;
2494 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2495 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002496
Eli Friedman410fc7a2012-03-30 01:13:43 +00002497 if (!RelatedRetType.isNull()) {
2498 // If we have a related result type, perform an extra conversion here.
2499 // FIXME: The diagnostics here don't really describe what is happening.
2500 InitializedEntity Entity =
2501 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosiercc6a9082012-06-20 18:51:04 +00002502
Eli Friedman410fc7a2012-03-30 01:13:43 +00002503 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2504 RetValExp);
2505 if (Res.isInvalid()) {
2506 // FIXME: Cleanup temporaries here, anyway?
2507 return StmtError();
2508 }
2509 RetValExp = Res.takeAs<Expr>();
2510 }
2511
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002512 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2513 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2514 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002515
John McCallfa272342011-06-16 23:24:51 +00002516 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002517 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002518 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002519 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002520 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002521 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002522 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002523 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002524 if (Res.isInvalid()) {
2525 // FIXME: Cleanup temporaries here, anyway?
2526 return StmtError();
2527 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002528
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002529 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002531 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
John McCallacf0ee52010-10-08 02:01:28 +00002534 if (RetValExp) {
2535 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00002536 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00002537 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002538 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002540
2541 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002542 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002543 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002544 !CurContext->isDependentContext())
2545 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00002546
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002547 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002548}
2549
John McCalldadc5752010-08-24 06:29:42 +00002550StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002551Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002552 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002553 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002554 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002555 if (Var && Var->isInvalidDecl())
2556 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
John McCallb268a282010-08-23 23:25:46 +00002558 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002559}
2560
John McCalldadc5752010-08-24 06:29:42 +00002561StmtResult
John McCallb268a282010-08-23 23:25:46 +00002562Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2563 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002564}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002565
John McCalldadc5752010-08-24 06:29:42 +00002566StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002568 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002569 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002570 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2571
John McCallaab3e412010-08-25 08:40:02 +00002572 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002573 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002574 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002575 CatchStmts.data(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002576 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002577 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002578}
2579
John McCall0bd3e402012-05-08 21:41:25 +00002580StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002581 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00002582 ExprResult Result = DefaultLvalueConversion(Throw);
2583 if (Result.isInvalid())
2584 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002585
John McCall0bd3e402012-05-08 21:41:25 +00002586 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregor2900c162010-04-22 21:44:01 +00002587 QualType ThrowType = Throw->getType();
2588 // Make sure the expression type is an ObjC pointer or "void *".
2589 if (!ThrowType->isDependentType() &&
2590 !ThrowType->isObjCObjectPointerType()) {
2591 const PointerType *PT = ThrowType->getAs<PointerType>();
2592 if (!PT || !PT->getPointeeType()->isVoidType())
2593 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2594 << Throw->getType() << Throw->getSourceRange());
2595 }
2596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002597
John McCallb268a282010-08-23 23:25:46 +00002598 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002599}
2600
John McCalldadc5752010-08-24 06:29:42 +00002601StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002603 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002604 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002605 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2606
John McCallb268a282010-08-23 23:25:46 +00002607 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002608 // @throw without an expression designates a rethrow (which much occur
2609 // in the context of an @catch clause).
2610 Scope *AtCatchParent = CurScope;
2611 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2612 AtCatchParent = AtCatchParent->getParent();
2613 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002614 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002615 }
John McCallb268a282010-08-23 23:25:46 +00002616 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002617}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002618
John McCalld9bb7432011-07-27 21:50:02 +00002619ExprResult
2620Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2621 ExprResult result = DefaultLvalueConversion(operand);
2622 if (result.isInvalid())
2623 return ExprError();
2624 operand = result.take();
2625
2626 // Make sure the expression type is an ObjC pointer or "void *".
2627 QualType type = operand->getType();
2628 if (!type->isDependentType() &&
2629 !type->isObjCObjectPointerType()) {
2630 const PointerType *pointerType = type->getAs<PointerType>();
2631 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2632 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2633 << type << operand->getSourceRange();
2634 }
2635
2636 // The operand to @synchronized is a full-expression.
2637 return MaybeCreateExprWithCleanups(operand);
2638}
2639
John McCalldadc5752010-08-24 06:29:42 +00002640StmtResult
John McCallb268a282010-08-23 23:25:46 +00002641Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2642 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002643 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002644 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002645 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002646}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002647
2648/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2649/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002650StmtResult
John McCall48871652010-08-21 09:40:31 +00002651Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002652 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002653 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002654 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002655 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002656 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002657}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002658
John McCall31168b02011-06-15 23:02:42 +00002659StmtResult
2660Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2661 getCurFunction()->setHasBranchProtectedScope();
2662 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2663}
2664
Dan Gohman28ade552010-07-26 21:25:24 +00002665namespace {
2666
Sebastian Redl63c4da02009-07-29 17:15:45 +00002667class TypeWithHandler {
2668 QualType t;
2669 CXXCatchStmt *stmt;
2670public:
2671 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2672 : t(type), stmt(statement) {}
2673
John McCall8ccfcb52009-09-24 19:53:00 +00002674 // An arbitrary order is fine as long as it places identical
2675 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002676 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002677 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002678 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002679 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002680 return false;
2681 else
2682 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Sebastian Redl63c4da02009-07-29 17:15:45 +00002685 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002686 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Sebastian Redl63c4da02009-07-29 17:15:45 +00002689 CXXCatchStmt *getCatchStmt() const { return stmt; }
2690 SourceLocation getTypeSpecStartLoc() const {
2691 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2692 }
2693};
2694
Dan Gohman28ade552010-07-26 21:25:24 +00002695}
2696
Sebastian Redl9b244a82008-12-22 21:35:02 +00002697/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2698/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002699StmtResult
John McCallb268a282010-08-23 23:25:46 +00002700Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002701 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002702 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002703 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002704 !getSourceManager().isInSystemHeader(TryLoc))
2705 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002706
Sebastian Redl9b244a82008-12-22 21:35:02 +00002707 unsigned NumHandlers = RawHandlers.size();
2708 assert(NumHandlers > 0 &&
2709 "The parser shouldn't call this if there are no handlers.");
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002710 Stmt **Handlers = RawHandlers.data();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002711
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002712 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002713
2714 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002715 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002716 if (!Handler->getExceptionDecl()) {
2717 if (i < NumHandlers - 1)
2718 return StmtError(Diag(Handler->getLocStart(),
2719 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002720
Sebastian Redl63c4da02009-07-29 17:15:45 +00002721 continue;
2722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Sebastian Redl63c4da02009-07-29 17:15:45 +00002724 const QualType CaughtType = Handler->getCaughtType();
2725 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2726 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002727 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002728
2729 // Detect handlers for the same type as an earlier one.
2730 if (NumHandlers > 1) {
2731 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002732
Sebastian Redl63c4da02009-07-29 17:15:45 +00002733 TypeWithHandler prev = TypesWithHandlers[0];
2734 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2735 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002736
Sebastian Redl63c4da02009-07-29 17:15:45 +00002737 if (curr == prev) {
2738 Diag(curr.getTypeSpecStartLoc(),
2739 diag::warn_exception_caught_by_earlier_handler)
2740 << curr.getCatchStmt()->getCaughtType().getAsString();
2741 Diag(prev.getTypeSpecStartLoc(),
2742 diag::note_previous_exception_handler)
2743 << prev.getCatchStmt()->getCaughtType().getAsString();
2744 }
Mike Stump11289f42009-09-09 15:08:12 +00002745
Sebastian Redl63c4da02009-07-29 17:15:45 +00002746 prev = curr;
2747 }
2748 }
Mike Stump11289f42009-09-09 15:08:12 +00002749
John McCallaab3e412010-08-25 08:40:02 +00002750 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002751
Sebastian Redl9b244a82008-12-22 21:35:02 +00002752 // FIXME: We should detect handlers that cannot catch anything because an
2753 // earlier handler catches a superclass. Need to find a method that is not
2754 // quadratic for this.
2755 // Neither of these are explicitly forbidden, but every compiler detects them
2756 // and warns.
2757
John McCallb268a282010-08-23 23:25:46 +00002758 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002759 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002760}
John Wiegley1c0675e2011-04-28 01:08:34 +00002761
2762StmtResult
2763Sema::ActOnSEHTryBlock(bool IsCXXTry,
2764 SourceLocation TryLoc,
2765 Stmt *TryBlock,
2766 Stmt *Handler) {
2767 assert(TryBlock && Handler);
2768
2769 getCurFunction()->setHasBranchProtectedScope();
2770
2771 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2772}
2773
2774StmtResult
2775Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2776 Expr *FilterExpr,
2777 Stmt *Block) {
2778 assert(FilterExpr && Block);
2779
2780 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002781 return StmtError(Diag(FilterExpr->getExprLoc(),
2782 diag::err_filter_expression_integral)
2783 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002784 }
2785
2786 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2787}
2788
2789StmtResult
2790Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2791 Stmt *Block) {
2792 assert(Block);
2793 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2794}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002795
2796StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2797 bool IsIfExists,
2798 NestedNameSpecifierLoc QualifierLoc,
2799 DeclarationNameInfo NameInfo,
2800 Stmt *Nested)
2801{
2802 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00002803 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002804 cast<CompoundStmt>(Nested));
2805}
2806
2807
Chad Rosier02a84392012-08-10 17:56:09 +00002808StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002809 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00002810 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002811 UnqualifiedId &Name,
2812 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00002813 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002814 SS.getWithLocInContext(Context),
2815 GetNameFromUnqualifiedId(Name),
2816 Nested);
2817}