blob: f923f61ce61cad2a2c21a4ad72e666ec7b6cfe01 [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"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000021#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000022#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000023#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/Initialization.h"
28#include "clang/Sema/Lookup.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000031#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000038
Richard Smith945f8d32013-01-14 22:39:08 +000039StmtResult Sema::ActOnExprStmt(ExprResult FE) {
40 if (FE.isInvalid())
41 return StmtError();
42
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
45 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000046 return StmtError();
47
Chris Lattner903eb512008-07-25 23:18:17 +000048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000051
Chris Lattner903eb512008-07-25 23:18:17 +000052 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000053 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000054}
55
56
John McCalleaef89b2013-03-22 02:10:40 +000057StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
59 return StmtError();
60}
61
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000062StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000063 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000065}
66
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000067StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000069 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000070
Chris Lattnercbafe8d2009-04-12 20:13:14 +000071 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000073
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000074 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000075}
Chris Lattneraf8d5812006-11-10 05:07:45 +000076
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000077void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000078 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000079
Douglas Gregor2eb1c572013-04-08 20:52:24 +000080 // If we don't have a declaration, or we have an invalid declaration,
81 // just return.
82 if (DG.isNull() || !DG.isSingleDecl())
83 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
87 return;
88
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
91 if (!var) {
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
94 return;
95 }
John McCall31168b02011-06-15 23:02:42 +000096
John McCalld4631322011-06-17 06:42:21 +000097 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +000099 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000104 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000105 QualType type = var->getType();
106
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000114 }
115 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000116}
117
Richard Trieu99e1c952014-03-11 03:11:08 +0000118/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120///
121/// Adding a cast to void (or other expression wrappers) will prevent the
122/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000123static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000125 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000128 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000129 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
Richard Trieu99e1c952014-03-11 03:11:08 +0000131 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000132 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 switch (Op->getOperator()) {
137 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000138 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000139 case OO_EqualEqual:
140 case OO_ExclaimEqual:
141 IsRelational = false;
142 break;
143 case OO_Less:
144 case OO_Greater:
145 case OO_GreaterEqual:
146 case OO_LessEqual:
147 IsRelational = true;
148 break;
149 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000150
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154 } else {
155 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000156 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000157 }
158
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000162 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000163
Chandler Carruthe2669392011-08-17 09:34:37 +0000164 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000166
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 if (IsNotEqual)
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
173 else
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
176 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000177
178 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000179}
180
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000181void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
184
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000185 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186 if (!E)
187 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000188
189 // If we are in an unevaluated expression context, then there can be no unused
190 // results because the results aren't expected to be used in the first place.
191 if (isUnevaluatedContext())
192 return;
193
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000195 // In most cases, we don't want to warn if the expression is written in a
196 // macro body, or if the macro comes from a system header. If the offending
197 // expression is a call to a function with the warn_unused_result attribute,
198 // we warn no matter the location. Because of the order in which the various
199 // checks need to happen, we factor out the macro-related test here.
200 bool ShouldSuppress =
201 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
202 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000203
Eli Friedmanc11535c2012-05-24 00:47:05 +0000204 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000205 SourceLocation Loc;
206 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208 return;
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattner6dc7e572012-08-31 22:39:21 +0000210 // If this is a GNU statement expression expanded from a macro, it is probably
211 // unused because it is a function-like macro that can be used as either an
212 // expression or statement. Don't warn, because it is almost certainly a
213 // false positive.
214 if (isa<StmtExpr>(E) && Loc.isMacroID())
215 return;
216
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000217 // Okay, we have an unused result. Depending on what the base expression is,
218 // we might want to make a more specific diagnostic. Check for one of these
219 // cases now.
220 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000222 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
224 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000225
Chandler Carruthe2669392011-08-17 09:34:37 +0000226 if (DiagnoseUnusedComparison(*this, E))
227 return;
228
Eli Friedmanc11535c2012-05-24 00:47:05 +0000229 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000231 if (E->getType()->isVoidType())
232 return;
233
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000235 // a more specific message to make it clear what is happening. If the call
236 // is written in a macro body, only warn if it has the warn_unused_result
237 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000238 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000239 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000240 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000241 return;
242 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000243 if (ShouldSuppress)
244 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000245 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
247 return;
248 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000249 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
251 return;
252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000254 } else if (ShouldSuppress)
255 return;
256
257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000259 Diag(Loc, diag::err_arc_unused_init_message) << R1;
260 return;
261 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000262 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000263 if (MD) {
264 if (MD->hasAttr<WarnUnusedResultAttr>()) {
265 Diag(Loc, diag::warn_unused_result) << R1 << R2;
266 return;
267 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000268 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000269 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
270 const Expr *Source = POE->getSyntacticForm();
271 if (isa<ObjCSubscriptRefExpr>(Source))
272 DiagID = diag::warn_unused_container_subscript_expr;
273 else
274 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000275 } else if (const CXXFunctionalCastExpr *FC
276 = dyn_cast<CXXFunctionalCastExpr>(E)) {
277 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
278 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
279 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000280 }
John McCall2351cb92010-04-06 22:24:14 +0000281 // Diagnose "(void*) blah" as a typo for "(void) blah".
282 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
283 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
284 QualType T = TI->getType();
285
286 // We really do want to use the non-canonical type here.
287 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000288 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000289
290 Diag(Loc, diag::warn_unused_voidptr)
291 << FixItHint::CreateRemoval(TL.getStarLoc());
292 return;
293 }
294 }
295
Eli Friedmanc11535c2012-05-24 00:47:05 +0000296 if (E->isGLValue() && E->getType().isVolatileQualified()) {
297 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
298 return;
299 }
300
Craig Topperc3ec1492014-05-26 06:22:03 +0000301 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000302}
303
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000304void Sema::ActOnStartOfCompoundStmt() {
305 PushCompoundScope();
306}
307
308void Sema::ActOnFinishOfCompoundStmt() {
309 PopCompoundScope();
310}
311
312sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
313 return getCurFunction()->CompoundScopes.back();
314}
315
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000316StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
317 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
318 const unsigned NumElts = Elts.size();
319
Chris Lattnerd864daf2007-08-27 04:29:41 +0000320 // If we're in C89 mode, check that we don't have any decls after stmts. If
321 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000322 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000323 // Note that __extension__ can be around a decl.
324 unsigned i = 0;
325 // Skip over all declarations.
326 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
327 /*empty*/;
328
329 // We found the end of the list or a statement. Scan for another declstmt.
330 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
331 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattnerd864daf2007-08-27 04:29:41 +0000333 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000334 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000335 Diag(D->getLocation(), diag::ext_mixed_decls_code);
336 }
337 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000338 // Warn about unused expressions in statements.
339 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000340 // Ignore statements that are last in a statement expression.
341 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000342 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000343
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000344 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000345 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000346
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000347 // Check for suspicious empty body (null statement) in `for' and `while'
348 // statements. Don't do anything for template instantiations, this just adds
349 // noise.
350 if (NumElts != 0 && !CurrentInstantiationScope &&
351 getCurCompoundScope().HasEmptyLoopBodies) {
352 for (unsigned i = 0; i != NumElts - 1; ++i)
353 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
354 }
355
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000356 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000357}
358
John McCalldadc5752010-08-24 06:29:42 +0000359StmtResult
John McCallb268a282010-08-23 23:25:46 +0000360Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
361 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000362 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000363 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000364
John McCallaab3e412010-08-25 08:40:02 +0000365 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000366 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000367 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000368 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000369
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000370 ExprResult LHS =
371 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
372 if (!getLangOpts().CPlusPlus11)
373 return VerifyIntegerConstantExpression(E);
374 if (Expr *CondExpr =
375 getCurFunction()->SwitchStack.back()->getCond()) {
376 QualType CondType = CondExpr->getType();
377 llvm::APSInt TempVal;
378 return CheckConvertedConstantExpression(E, CondType, TempVal,
379 CCEK_CaseValue);
380 }
381 return ExprError();
382 });
383 if (LHS.isInvalid())
384 return StmtError();
385 LHSVal = LHS.get();
386
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000387 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000388 // C99 6.8.4.2p3: The expression shall be an integer constant.
389 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000390 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000391 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000392 if (!LHSVal)
393 return StmtError();
394 }
Richard Smithf8379a02012-01-18 23:55:52 +0000395
396 // GCC extension: The expression shall be an integer constant.
397
Richard Smithf4c51d92012-02-04 09:53:13 +0000398 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000399 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000400 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000401 }
402 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000403
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000404 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000405 getLangOpts().CPlusPlus11);
406 if (LHS.isInvalid())
407 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000408
Richard Smith5b555da2014-11-20 01:24:12 +0000409 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
410 getLangOpts().CPlusPlus11)
411 : ExprResult();
412 if (RHS.isInvalid())
413 return StmtError();
414
415 CaseStmt *CS = new (Context)
416 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000417 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000418 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000419}
420
Chris Lattner34a22092009-03-04 04:23:07 +0000421/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000422void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000423 DiagnoseUnusedExprResult(SubStmt);
424
Chris Lattner34a22092009-03-04 04:23:07 +0000425 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000426 CS->setSubStmt(SubStmt);
427}
428
John McCalldadc5752010-08-24 06:29:42 +0000429StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000430Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000431 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000432 DiagnoseUnusedExprResult(SubStmt);
433
John McCallaab3e412010-08-25 08:40:02 +0000434 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000435 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000436 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000437 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000438
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000439 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000440 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000441 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000442}
443
John McCalldadc5752010-08-24 06:29:42 +0000444StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000445Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
446 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000447 // If the label was multiply defined, reject it now.
448 if (TheDecl->getStmt()) {
449 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
450 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000452 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000453
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000454 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000455 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
456 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000457 if (!TheDecl->isGnuLocal()) {
458 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000459 if (!TheDecl->isMSAsmLabel()) {
460 // Don't update the location of MS ASM labels. These will result in
461 // a diagnostic, and changing the location here will mess that up.
462 TheDecl->setLocation(IdentLoc);
463 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000464 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000465 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000466}
467
Richard Smithc202b282012-04-14 00:33:13 +0000468StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000469 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000470 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000471 // Fill in the declaration and return it.
472 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000473 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000474}
475
John McCalldadc5752010-08-24 06:29:42 +0000476StmtResult
John McCall48871652010-08-21 09:40:31 +0000477Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000478 Stmt *thenStmt, SourceLocation ElseLoc,
479 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000480 // If the condition was invalid, discard the if statement. We could recover
481 // better by replacing it with a valid expr, but don't do that yet.
482 if (!CondVal.get() && !CondVar) {
483 getCurFunction()->setHasDroppedStmt();
484 return StmtError();
485 }
486
John McCalldadc5752010-08-24 06:29:42 +0000487 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000488
Craig Topperc3ec1492014-05-26 06:22:03 +0000489 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000490 if (CondVar) {
491 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000492 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000493 if (CondResult.isInvalid())
494 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000495 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000496 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000497 if (!ConditionExpr)
498 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000500 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000501
John McCallb268a282010-08-23 23:25:46 +0000502 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000503 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
504 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000505 }
506
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000507 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000508
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000509 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
510 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000511}
Steve Naroff86272ea2007-05-29 02:14:17 +0000512
Chris Lattner67998452007-08-23 18:29:20 +0000513namespace {
514 struct CaseCompareFunctor {
515 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
516 const llvm::APSInt &RHS) {
517 return LHS.first < RHS;
518 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
521 return LHS.first < RHS.first;
522 }
Chris Lattner67998452007-08-23 18:29:20 +0000523 bool operator()(const llvm::APSInt &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS < RHS.first;
526 }
527 };
528}
529
Chris Lattner4b2ff022007-09-21 18:15:22 +0000530/// CmpCaseVals - Comparison predicate for sorting case values.
531///
532static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
533 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
534 if (lhs.first < rhs.first)
535 return true;
536
537 if (lhs.first == rhs.first &&
538 lhs.second->getCaseLoc().getRawEncoding()
539 < rhs.second->getCaseLoc().getRawEncoding())
540 return true;
541 return false;
542}
543
Douglas Gregorbd6839732010-02-08 22:24:16 +0000544/// CmpEnumVals - Comparison predicate for sorting enumeration values.
545///
546static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
547 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
548{
549 return lhs.first < rhs.first;
550}
551
552/// EqEnumVals - Comparison preficate for uniqing enumeration values.
553///
554static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
555 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
556{
557 return lhs.first == rhs.first;
558}
559
Chris Lattnera96d4272009-10-16 16:45:22 +0000560/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
561/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000562static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
563 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
564 expr = cleanups->getSubExpr();
565 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
566 if (impcast->getCastKind() != CK_IntegralCast) break;
567 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000568 }
569 return expr->getType();
570}
571
John McCalldadc5752010-08-24 06:29:42 +0000572StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000574 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000575 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000576
Craig Topperc3ec1492014-05-26 06:22:03 +0000577 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000578 if (CondVar) {
579 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000580 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
581 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000582 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000584 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000585 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
John McCallb268a282010-08-23 23:25:46 +0000587 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000588 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Douglas Gregore2b37442012-05-04 22:38:52 +0000590 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
591 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000592
Douglas Gregore2b37442012-05-04 22:38:52 +0000593 public:
594 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000595 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
596 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000597
Craig Toppere14c0f82014-03-12 04:55:44 +0000598 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
599 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000600 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
601 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000602
Craig Toppere14c0f82014-03-12 04:55:44 +0000603 SemaDiagnosticBuilder diagnoseIncomplete(
604 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000605 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
606 << T << Cond->getSourceRange();
607 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000608
Craig Toppere14c0f82014-03-12 04:55:44 +0000609 SemaDiagnosticBuilder diagnoseExplicitConv(
610 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000611 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
612 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000613
Craig Toppere14c0f82014-03-12 04:55:44 +0000614 SemaDiagnosticBuilder noteExplicitConv(
615 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000616 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
617 << ConvTy->isEnumeralType() << ConvTy;
618 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000619
Craig Toppere14c0f82014-03-12 04:55:44 +0000620 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
621 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000622 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
623 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000624
Craig Toppere14c0f82014-03-12 04:55:44 +0000625 SemaDiagnosticBuilder noteAmbiguous(
626 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000627 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
628 << ConvTy->isEnumeralType() << ConvTy;
629 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000630
Craig Toppere14c0f82014-03-12 04:55:44 +0000631 SemaDiagnosticBuilder diagnoseConversion(
632 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000633 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000634 }
635 } SwitchDiagnoser(Cond);
636
Richard Smithccc11812013-05-21 19:05:48 +0000637 CondResult =
638 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000639 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000640 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000641
John McCall5939b162011-08-06 07:30:58 +0000642 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
643 CondResult = UsualUnaryConversions(Cond);
644 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000645 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000646
John McCall48871652010-08-21 09:40:31 +0000647 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000648 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000649 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000650 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000651 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000652 }
John McCalla95172b2010-08-01 00:26:45 +0000653
John McCallaab3e412010-08-25 08:40:02 +0000654 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655
John McCallb268a282010-08-23 23:25:46 +0000656 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000657 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000658 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000659}
660
Gabor Greif16e02862010-10-01 22:05:14 +0000661static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000662 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000663 Val.setIsSigned(IsSigned);
664}
665
Richard Smith077d0832014-08-04 00:40:48 +0000666/// Check the specified case value is in range for the given unpromoted switch
667/// type.
668static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
669 unsigned UnpromotedWidth, bool UnpromotedSign) {
670 // If the case value was signed and negative and the switch expression is
671 // unsigned, don't bother to warn: this is implementation-defined behavior.
672 // FIXME: Introduce a second, default-ignored warning for this case?
673 if (UnpromotedWidth < Val.getBitWidth()) {
674 llvm::APSInt ConvVal(Val);
675 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
676 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
677 // FIXME: Use different diagnostics for overflow in conversion to promoted
678 // type versus "switch expression cannot have this value". Use proper
679 // IntRange checking rather than just looking at the unpromoted type here.
680 if (ConvVal != Val)
681 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
682 << ConvVal.toString(10);
683 }
684}
685
Alexis Hunt724f14e2014-11-28 00:53:20 +0000686typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
687
Dmitri Gribenko58683752013-12-05 22:52:07 +0000688/// Returns true if we should emit a diagnostic about this case expression not
689/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000690static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000691 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000692 const Expr *CaseExpr,
693 EnumValsTy::iterator &EI,
694 EnumValsTy::iterator &EIEnd,
695 const llvm::APSInt &Val) {
696 bool FlagType = ED->hasAttr<FlagEnumAttr>();
697
698 if (const DeclRefExpr *DRE =
699 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000700 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000701 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000702 QualType EnumType = S.Context.getTypeDeclType(ED);
703 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
704 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000705 return false;
706 }
707 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000708
709 if (FlagType) {
710 return !S.IsValueInFlagEnum(ED, Val, false);
711 } else {
712 while (EI != EIEnd && EI->first < Val)
713 EI++;
714
715 if (EI != EIEnd && EI->first == Val)
716 return false;
717 }
718
Dmitri Gribenko58683752013-12-05 22:52:07 +0000719 return true;
720}
721
John McCalldadc5752010-08-24 06:29:42 +0000722StmtResult
John McCallb268a282010-08-23 23:25:46 +0000723Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
724 Stmt *BodyStmt) {
725 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000726 assert(SS == getCurFunction()->SwitchStack.back() &&
727 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000728
David Majnemer418ad3f2014-12-15 07:46:12 +0000729 getCurFunction()->SwitchStack.pop_back();
730
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000731 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000732 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000733
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000734 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000735 if (!CondExpr) return StmtError();
736
737 QualType CondType = CondExpr->getType();
738
John McCalld3dfbd62010-05-18 03:19:21 +0000739 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000740 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000741 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000742
Chris Lattnera96d4272009-10-16 16:45:22 +0000743 // C++ 6.4.2.p2:
744 // Integral promotions are performed (on the switch condition).
745 //
746 // A case value unrepresentable by the original switch condition
747 // type (before the promotion) doesn't make sense, even when it can
748 // be represented by the promoted type. Therefore we need to find
749 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000750 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000751 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000753 // appropriate type now, just return an error.
754 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000755 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000756
Chris Lattner4ebae652010-04-16 23:34:13 +0000757 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000758 // switch(bool_expr) {...} is often a programmer error, e.g.
759 // switch(n && mask) { ... } // Doh - should be "n & mask".
760 // One can always use an if statement instead of switch(bool_expr).
761 Diag(SwitchLoc, diag::warn_bool_switch_condition)
762 << CondExpr->getSourceRange();
763 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000764 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000765
Richard Smith077d0832014-08-04 00:40:48 +0000766 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000767 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000768 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000769 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000770 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
771 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
772
773 // Get the width and signedness that the condition might actually have, for
774 // warning purposes.
775 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
776 // type.
777 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000778 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000779 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000780 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000782 // Accumulate all of the case values in a vector so that we can sort them
783 // and detect duplicates. This vector contains the APInt for the case after
784 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000785 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000786 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000787
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000788 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000789 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
790 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattner10cb5e52007-08-23 06:23:56 +0000794 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000796 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000797 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000798
Anders Carlsson51873c22007-07-22 07:07:56 +0000799 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000800 if (TheDefaultStmt) {
801 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000802 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000803
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000804 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000805 // we'll return a valid AST. This requires recursing down the AST and
806 // finding it, not something we are set up to do right now. For now,
807 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000808 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000809 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000810 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000812 } else {
813 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000814
Chris Lattnera65e1f32008-01-16 19:17:22 +0000815 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000816
817 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
818 HasDependentValue = true;
819 break;
820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Richard Smithf8379a02012-01-18 23:55:52 +0000822 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000823
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000824 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000825 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
826 // constant expression of the promoted type of the switch condition.
827 ExprResult ConvLo =
828 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
829 if (ConvLo.isInvalid()) {
830 CaseListIsErroneous = true;
831 continue;
832 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000833 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000834 } else {
835 // We already verified that the expression has a i-c-e value (C99
836 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000837 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000838
839 // If the LHS is not the same type as the condition, insert an implicit
840 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000841 Lo = DefaultLvalueConversion(Lo).get();
842 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000843 }
844
Richard Smith077d0832014-08-04 00:40:48 +0000845 // Check the unconverted value is within the range of possible values of
846 // the switch expression.
847 checkCaseValue(*this, Lo->getLocStart(), LoVal,
848 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
849
850 // Convert the value to the same width/sign as the condition.
851 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000852
Chris Lattnera65e1f32008-01-16 19:17:22 +0000853 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattner10cb5e52007-08-23 06:23:56 +0000855 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000856 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000857 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000858 CS->getRHS()->isValueDependent()) {
859 HasDependentValue = true;
860 break;
861 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000862 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000863 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000864 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000865 }
866 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000867
868 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000869 // If we don't have a default statement, check whether the
870 // condition is constant.
871 llvm::APSInt ConstantCondValue;
872 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000873 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000874 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
875 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000876 assert(!HasConstantCond ||
877 (ConstantCondValue.getBitWidth() == CondWidth &&
878 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000879 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000880 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000881
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000882 // Sort all the scalar case values so we can easily detect duplicates.
883 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
884
885 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000886 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
887 if (ShouldCheckConstantCond &&
888 CaseVals[i].first == ConstantCondValue)
889 ShouldCheckConstantCond = false;
890
891 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000892 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000893 // First, determine if either case value has a name
894 StringRef PrevString, CurrString;
895 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
896 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
897 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
898 PrevString = DeclRef->getDecl()->getName();
899 }
900 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
901 CurrString = DeclRef->getDecl()->getName();
902 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000903 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000904 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000905
906 if (PrevString == CurrString)
907 Diag(CaseVals[i].second->getLHS()->getLocStart(),
908 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000909 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000910 else
911 Diag(CaseVals[i].second->getLHS()->getLocStart(),
912 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000913 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
914 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000915 CaseValStr;
916
John McCalld3dfbd62010-05-18 03:19:21 +0000917 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000918 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000919 // FIXME: We really want to remove the bogus case stmt from the
920 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000921 CaseListIsErroneous = true;
922 }
923 }
924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000926 // Detect duplicate case ranges, which usually don't exist at all in
927 // the first place.
928 if (!CaseRanges.empty()) {
929 // Sort all the case ranges by their low value so we can easily detect
930 // overlaps between ranges.
931 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000933 // Scan the ranges, computing the high values and removing empty ranges.
934 std::vector<llvm::APSInt> HiVals;
935 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000936 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000937 CaseStmt *CR = CaseRanges[i].second;
938 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000939 llvm::APSInt HiVal;
940
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000941 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000942 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
943 // constant expression of the promoted type of the switch condition.
944 ExprResult ConvHi =
945 CheckConvertedConstantExpression(Hi, CondType, HiVal,
946 CCEK_CaseValue);
947 if (ConvHi.isInvalid()) {
948 CaseListIsErroneous = true;
949 continue;
950 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000951 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000952 } else {
953 HiVal = Hi->EvaluateKnownConstInt(Context);
954
955 // If the RHS is not the same type as the condition, insert an
956 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000957 Hi = DefaultLvalueConversion(Hi).get();
958 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Richard Smith077d0832014-08-04 00:40:48 +0000961 // Check the unconverted value is within the range of possible values of
962 // the switch expression.
963 checkCaseValue(*this, Hi->getLocStart(), HiVal,
964 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
965
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000966 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000967 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000968
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000969 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000970
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000971 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000972 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000973 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
974 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000975 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 CaseRanges.erase(CaseRanges.begin()+i);
977 --i, --e;
978 continue;
979 }
John McCalld3dfbd62010-05-18 03:19:21 +0000980
981 if (ShouldCheckConstantCond &&
982 LoVal <= ConstantCondValue &&
983 ConstantCondValue <= HiVal)
984 ShouldCheckConstantCond = false;
985
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000986 HiVals.push_back(HiVal);
987 }
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000989 // Rescan the ranges, looking for overlap with singleton values and other
990 // ranges. Since the range list is sorted, we only need to compare case
991 // ranges with their neighbors.
992 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
993 llvm::APSInt &CRLo = CaseRanges[i].first;
994 llvm::APSInt &CRHi = HiVals[i];
995 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000996
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000997 // Check to see whether the case range overlaps with any
998 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +0000999 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001000 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001001
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001002 // Find the smallest value >= the lower bound. If I is in the
1003 // case range, then we have overlap.
1004 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1005 CaseVals.end(), CRLo,
1006 CaseCompareFunctor());
1007 if (I != CaseVals.end() && I->first < CRHi) {
1008 OverlapVal = I->first; // Found overlap with scalar.
1009 OverlapStmt = I->second;
1010 }
Mike Stump11289f42009-09-09 15:08:12 +00001011
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001012 // Find the smallest value bigger than the upper bound.
1013 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1014 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1015 OverlapVal = (I-1)->first; // Found overlap with scalar.
1016 OverlapStmt = (I-1)->second;
1017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001019 // Check to see if this case stmt overlaps with the subsequent
1020 // case range.
1021 if (i && CRLo <= HiVals[i-1]) {
1022 OverlapVal = HiVals[i-1]; // Found overlap with range.
1023 OverlapStmt = CaseRanges[i-1].second;
1024 }
Mike Stump11289f42009-09-09 15:08:12 +00001025
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001026 if (OverlapStmt) {
1027 // If we have a duplicate, report it.
1028 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1029 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001030 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001031 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001032 // FIXME: We really want to remove the bogus case stmt from the
1033 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001034 CaseListIsErroneous = true;
1035 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001036 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001037 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001038
John McCalld3dfbd62010-05-18 03:19:21 +00001039 // Complain if we have a constant condition and we didn't find a match.
1040 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1041 // TODO: it would be nice if we printed enums as enums, chars as
1042 // chars, etc.
1043 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1044 << ConstantCondValue.toString(10)
1045 << CondExpr->getSourceRange();
1046 }
1047
1048 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001049 // values. We only issue a warning if there is not 'default:', but
1050 // we still do the analysis to preserve this information in the AST
1051 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001052 //
Chris Lattner51679082010-09-16 17:09:42 +00001053 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001054
Douglas Gregorbd6839732010-02-08 22:24:16 +00001055 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001056 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001057 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001058 EnumValsTy EnumVals;
1059
John McCalld3dfbd62010-05-18 03:19:21 +00001060 // Gather all enum values, set their type and sort them,
1061 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001062 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001063 llvm::APSInt Val = EDI->getInitVal();
1064 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001065 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001066 }
1067 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001068 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001069 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001070
1071 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001072 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001073 CI != CaseVals.end(); CI++) {
1074 Expr *CaseExpr = CI->second->getLHS();
1075 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1076 CI->first))
1077 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1078 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001079 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001080
David Blaikiee476f972012-01-22 02:31:55 +00001081 // See which of case ranges aren't in enum
1082 EI = EnumVals.begin();
1083 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001084 RI != CaseRanges.end(); RI++) {
1085 Expr *CaseExpr = RI->second->getLHS();
1086 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1087 RI->first))
1088 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1089 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001090
Chad Rosier02a84392012-08-10 17:56:09 +00001091 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001092 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1093 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001094
1095 CaseExpr = RI->second->getRHS();
1096 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1097 Hi))
1098 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1099 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001101
Ted Kremenekc42f3452010-09-09 00:05:53 +00001102 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001103 auto CI = CaseVals.begin();
1104 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001105 bool hasCasesNotInSwitch = false;
1106
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001107 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Alexis Hunt724f14e2014-11-28 00:53:20 +00001109 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001110 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001111 while (CI != CaseVals.end() && CI->first < EI->first)
1112 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001113
Douglas Gregorbd6839732010-02-08 22:24:16 +00001114 if (CI != CaseVals.end() && CI->first == EI->first)
1115 continue;
1116
Ted Kremenekc42f3452010-09-09 00:05:53 +00001117 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001118 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001119 llvm::APSInt Hi =
1120 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001121 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001122 if (EI->first <= Hi)
1123 break;
1124 }
1125
Ted Kremenekc42f3452010-09-09 00:05:53 +00001126 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001127 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001128 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001129 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131
David Blaikie60ac6382012-01-23 04:46:12 +00001132 if (TheDefaultStmt && UnhandledNames.empty())
1133 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001134
Chris Lattner51679082010-09-16 17:09:42 +00001135 // Produce a nice diagnostic if multiple values aren't handled.
1136 switch (UnhandledNames.size()) {
1137 case 0: break;
1138 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001139 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001140 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001141 << UnhandledNames[0];
1142 break;
1143 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001144 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001145 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001146 << UnhandledNames[0] << UnhandledNames[1];
1147 break;
1148 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001149 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1150 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001151 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1152 break;
1153 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001154 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1155 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001156 << (unsigned)UnhandledNames.size()
1157 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1158 break;
1159 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001160
1161 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001162 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001163 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001164 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001165
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001166 if (BodyStmt)
1167 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1168 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001169
Mike Stump87c57ac2009-05-16 07:39:55 +00001170 // FIXME: If the case list was broken is some way, we don't have a good system
1171 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001172 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001173 return StmtError();
1174
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001175 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001176}
1177
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001178void
1179Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1180 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001181 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001182 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001183
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001184 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001185 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001186 SrcType->isIntegerType()) {
1187 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1188 SrcExpr->isIntegerConstantExpr(Context)) {
1189 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001190 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001191 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1192
1193 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001194 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001195 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001196
Alexis Hunt724f14e2014-11-28 00:53:20 +00001197 if (ED->hasAttr<FlagEnumAttr>()) {
1198 if (!IsValueInFlagEnum(ED, RhsVal, true))
1199 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001200 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001201 } else {
1202 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1203 EnumValsTy;
1204 EnumValsTy EnumVals;
1205
1206 // Gather all enum values, set their type and sort them,
1207 // allowing easier comparison with rhs constant.
1208 for (auto *EDI : ED->enumerators()) {
1209 llvm::APSInt Val = EDI->getInitVal();
1210 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1211 EnumVals.push_back(std::make_pair(Val, EDI));
1212 }
1213 if (EnumVals.empty())
1214 return;
1215 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1216 EnumValsTy::iterator EIend =
1217 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1218
1219 // See which values aren't in the enum.
1220 EnumValsTy::const_iterator EI = EnumVals.begin();
1221 while (EI != EIend && EI->first < RhsVal)
1222 EI++;
1223 if (EI == EIend || EI->first != RhsVal) {
1224 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1225 << DstType.getUnqualifiedType();
1226 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001227 }
1228 }
1229 }
1230}
1231
John McCalldadc5752010-08-24 06:29:42 +00001232StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001234 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001235 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Craig Topperc3ec1492014-05-26 06:22:03 +00001237 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001238 if (CondVar) {
1239 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001240 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001241 if (CondResult.isInvalid())
1242 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001243 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001244 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001245 if (!ConditionExpr)
1246 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001247 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248
John McCallb268a282010-08-23 23:25:46 +00001249 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001250
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001251 if (isa<NullStmt>(Body))
1252 getCurCompoundScope().setHasEmptyLoopBodies();
1253
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001254 return new (Context)
1255 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001256}
1257
John McCalldadc5752010-08-24 06:29:42 +00001258StmtResult
John McCallb268a282010-08-23 23:25:46 +00001259Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001260 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001261 Expr *Cond, SourceLocation CondRParen) {
1262 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001263
Serge Pavlov09f99242014-01-23 15:05:00 +00001264 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001265 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001266 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001267 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001268 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001269
Richard Smith945f8d32013-01-14 22:39:08 +00001270 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001271 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001272 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001273 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001274
John McCallb268a282010-08-23 23:25:46 +00001275 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001276
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001277 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001278}
1279
Richard Trieu451a5db2012-04-30 18:01:30 +00001280namespace {
1281 // This visitor will traverse a conditional statement and store all
1282 // the evaluated decls into a vector. Simple is set to true if none
1283 // of the excluded constructs are used.
1284 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001285 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001286 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001287 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001288 public:
1289 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001290
Craig Topper4dd9b432014-08-17 23:49:53 +00001291 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001292 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001293 Inherited(S.Context),
1294 Decls(Decls),
1295 Ranges(Ranges),
1296 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001297
Richard Trieu9d228802013-05-31 22:46:45 +00001298 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001299
Richard Trieu9d228802013-05-31 22:46:45 +00001300 // Replaces the method in EvaluatedExprVisitor.
1301 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001302 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001303 }
1304
1305 // Any Stmt not whitelisted will cause the condition to be marked complex.
1306 void VisitStmt(Stmt *S) {
1307 Simple = false;
1308 }
1309
1310 void VisitBinaryOperator(BinaryOperator *E) {
1311 Visit(E->getLHS());
1312 Visit(E->getRHS());
1313 }
1314
1315 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001316 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001317 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001318
Richard Trieu9d228802013-05-31 22:46:45 +00001319 void VisitUnaryOperator(UnaryOperator *E) {
1320 // Skip checking conditionals with derefernces.
1321 if (E->getOpcode() == UO_Deref)
1322 Simple = false;
1323 else
1324 Visit(E->getSubExpr());
1325 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001326
Richard Trieu9d228802013-05-31 22:46:45 +00001327 void VisitConditionalOperator(ConditionalOperator *E) {
1328 Visit(E->getCond());
1329 Visit(E->getTrueExpr());
1330 Visit(E->getFalseExpr());
1331 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001332
Richard Trieu9d228802013-05-31 22:46:45 +00001333 void VisitParenExpr(ParenExpr *E) {
1334 Visit(E->getSubExpr());
1335 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001336
Richard Trieu9d228802013-05-31 22:46:45 +00001337 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1338 Visit(E->getOpaqueValue()->getSourceExpr());
1339 Visit(E->getFalseExpr());
1340 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001341
Richard Trieu9d228802013-05-31 22:46:45 +00001342 void VisitIntegerLiteral(IntegerLiteral *E) { }
1343 void VisitFloatingLiteral(FloatingLiteral *E) { }
1344 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1345 void VisitCharacterLiteral(CharacterLiteral *E) { }
1346 void VisitGNUNullExpr(GNUNullExpr *E) { }
1347 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001348
Richard Trieu9d228802013-05-31 22:46:45 +00001349 void VisitDeclRefExpr(DeclRefExpr *E) {
1350 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1351 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001352
Richard Trieu9d228802013-05-31 22:46:45 +00001353 Ranges.push_back(E->getSourceRange());
1354
1355 Decls.insert(VD);
1356 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001357
1358 }; // end class DeclExtractor
1359
1360 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001361 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001362 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001363 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001364 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 public:
1367 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001368
Craig Topper4dd9b432014-08-17 23:49:53 +00001369 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001370 Stmt *Statement) :
1371 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1372 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001375 }
1376
Richard Trieu9d228802013-05-31 22:46:45 +00001377 void VisitReturnStmt(ReturnStmt *S) {
1378 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001379 }
1380
Richard Trieu9d228802013-05-31 22:46:45 +00001381 void VisitBreakStmt(BreakStmt *S) {
1382 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001383 }
1384
Richard Trieu9d228802013-05-31 22:46:45 +00001385 void VisitGotoStmt(GotoStmt *S) {
1386 FoundDecl = true;
1387 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001388
Richard Trieu9d228802013-05-31 22:46:45 +00001389 void VisitCastExpr(CastExpr *E) {
1390 if (E->getCastKind() == CK_LValueToRValue)
1391 CheckLValueToRValueCast(E->getSubExpr());
1392 else
1393 Visit(E->getSubExpr());
1394 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001395
Richard Trieu9d228802013-05-31 22:46:45 +00001396 void CheckLValueToRValueCast(Expr *E) {
1397 E = E->IgnoreParenImpCasts();
1398
1399 if (isa<DeclRefExpr>(E)) {
1400 return;
1401 }
1402
1403 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1404 Visit(CO->getCond());
1405 CheckLValueToRValueCast(CO->getTrueExpr());
1406 CheckLValueToRValueCast(CO->getFalseExpr());
1407 return;
1408 }
1409
1410 if (BinaryConditionalOperator *BCO =
1411 dyn_cast<BinaryConditionalOperator>(E)) {
1412 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1413 CheckLValueToRValueCast(BCO->getFalseExpr());
1414 return;
1415 }
1416
1417 Visit(E);
1418 }
1419
1420 void VisitDeclRefExpr(DeclRefExpr *E) {
1421 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1422 if (Decls.count(VD))
1423 FoundDecl = true;
1424 }
1425
1426 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001427
1428 }; // end class DeclMatcher
1429
1430 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1431 Expr *Third, Stmt *Body) {
1432 // Condition is empty
1433 if (!Second) return;
1434
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001435 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1436 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001437 return;
1438
1439 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1440 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001441 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001442 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001443 DE.Visit(Second);
1444
1445 // Don't analyze complex conditionals.
1446 if (!DE.isSimple()) return;
1447
1448 // No decls found.
1449 if (Decls.size() == 0) return;
1450
Richard Trieu0030f1d2012-05-04 03:01:54 +00001451 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001452 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1453 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001454 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001455 if ((*I)->getType().isVolatileQualified() ||
1456 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001457
1458 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1459 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1460 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1461 return;
1462
1463 // Load decl names into diagnostic.
1464 if (Decls.size() > 4)
1465 PDiag << 0;
1466 else {
1467 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001468 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1469 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001470 I != E; ++I)
1471 PDiag << (*I)->getDeclName();
1472 }
1473
1474 // Load SourceRanges into diagnostic if there is room.
1475 // Otherwise, load the SourceRange of the conditional expression.
1476 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001477 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001478 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001479 I != E; ++I)
1480 PDiag << *I;
1481 else
1482 PDiag << Second->getSourceRange();
1483
1484 S.Diag(Ranges.begin()->getBegin(), PDiag);
1485 }
1486
Richard Trieu4e7c9622013-08-06 21:31:54 +00001487 // If Statement is an incemement or decrement, return true and sets the
1488 // variables Increment and DRE.
1489 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1490 DeclRefExpr *&DRE) {
1491 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1492 switch (UO->getOpcode()) {
1493 default: return false;
1494 case UO_PostInc:
1495 case UO_PreInc:
1496 Increment = true;
1497 break;
1498 case UO_PostDec:
1499 case UO_PreDec:
1500 Increment = false;
1501 break;
1502 }
1503 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1504 return DRE;
1505 }
1506
1507 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1508 FunctionDecl *FD = Call->getDirectCallee();
1509 if (!FD || !FD->isOverloadedOperator()) return false;
1510 switch (FD->getOverloadedOperator()) {
1511 default: return false;
1512 case OO_PlusPlus:
1513 Increment = true;
1514 break;
1515 case OO_MinusMinus:
1516 Increment = false;
1517 break;
1518 }
1519 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1520 return DRE;
1521 }
1522
1523 return false;
1524 }
1525
Serge Pavlov09f99242014-01-23 15:05:00 +00001526 // A visitor to determine if a continue or break statement is a
1527 // subexpression.
1528 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1529 SourceLocation BreakLoc;
1530 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001531 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001532 BreakContinueFinder(Sema &S, Stmt* Body) :
1533 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001534 Visit(Body);
1535 }
1536
Serge Pavlov09f99242014-01-23 15:05:00 +00001537 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001538
1539 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001540 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001541 }
1542
Serge Pavlov09f99242014-01-23 15:05:00 +00001543 void VisitBreakStmt(BreakStmt* E) {
1544 BreakLoc = E->getBreakLoc();
1545 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001546
Serge Pavlov09f99242014-01-23 15:05:00 +00001547 bool ContinueFound() { return ContinueLoc.isValid(); }
1548 bool BreakFound() { return BreakLoc.isValid(); }
1549 SourceLocation GetContinueLoc() { return ContinueLoc; }
1550 SourceLocation GetBreakLoc() { return BreakLoc; }
1551
1552 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001553
1554 // Emit a warning when a loop increment/decrement appears twice per loop
1555 // iteration. The conditions which trigger this warning are:
1556 // 1) The last statement in the loop body and the third expression in the
1557 // for loop are both increment or both decrement of the same variable
1558 // 2) No continue statements in the loop body.
1559 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1560 // Return when there is nothing to check.
1561 if (!Body || !Third) return;
1562
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001563 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1564 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001565 return;
1566
1567 // Get the last statement from the loop body.
1568 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1569 if (!CS || CS->body_empty()) return;
1570 Stmt *LastStmt = CS->body_back();
1571 if (!LastStmt) return;
1572
1573 bool LoopIncrement, LastIncrement;
1574 DeclRefExpr *LoopDRE, *LastDRE;
1575
1576 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1577 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1578
1579 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001580 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001581 if (LoopIncrement != LastIncrement ||
1582 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1583
Serge Pavlov09f99242014-01-23 15:05:00 +00001584 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001585
1586 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1587 << LastDRE->getDecl() << LastIncrement;
1588 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1589 << LoopIncrement;
1590 }
1591
Richard Trieu451a5db2012-04-30 18:01:30 +00001592} // end namespace
1593
Serge Pavlov09f99242014-01-23 15:05:00 +00001594
1595void Sema::CheckBreakContinueBinding(Expr *E) {
1596 if (!E || getLangOpts().CPlusPlus)
1597 return;
1598 BreakContinueFinder BCFinder(*this, E);
1599 Scope *BreakParent = CurScope->getBreakParent();
1600 if (BCFinder.BreakFound() && BreakParent) {
1601 if (BreakParent->getFlags() & Scope::SwitchScope) {
1602 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1603 } else {
1604 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1605 << "break";
1606 }
1607 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1608 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1609 << "continue";
1610 }
1611}
1612
John McCalldadc5752010-08-24 06:29:42 +00001613StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001614Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001615 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001616 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001617 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001618 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001619 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001620 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1621 // declare identifiers for objects having storage class 'auto' or
1622 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001623 for (auto *DI : DS->decls()) {
1624 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001625 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001626 VD = nullptr;
1627 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001628 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1629 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001630 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001631 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001632 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001633 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001634
Serge Pavlov09f99242014-01-23 15:05:00 +00001635 CheckBreakContinueBinding(second.get());
1636 CheckBreakContinueBinding(third.get());
1637
Richard Trieu451a5db2012-04-30 18:01:30 +00001638 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001639 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001640
John McCalldadc5752010-08-24 06:29:42 +00001641 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001642 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001643 if (secondVar) {
1644 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001645 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001646 if (SecondResult.isInvalid())
1647 return StmtError();
1648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001650 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651
Anders Carlsson1682af52009-08-01 01:39:59 +00001652 DiagnoseUnusedExprResult(First);
1653 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001654 DiagnoseUnusedExprResult(Body);
1655
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001656 if (isa<NullStmt>(Body))
1657 getCurCompoundScope().setHasEmptyLoopBodies();
1658
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001659 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1660 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001661}
1662
John McCall34376a62010-12-04 03:47:34 +00001663/// In an Objective C collection iteration statement:
1664/// for (x in y)
1665/// x can be an arbitrary l-value expression. Bind it up as a
1666/// full-expression.
1667StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001668 // Reduce placeholder expressions here. Note that this rejects the
1669 // use of pseudo-object l-values in this position.
1670 ExprResult result = CheckPlaceholderExpr(E);
1671 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001672 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001673
Richard Smith945f8d32013-01-14 22:39:08 +00001674 ExprResult FullExpr = ActOnFinishFullExpr(E);
1675 if (FullExpr.isInvalid())
1676 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001677 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001678}
1679
John McCall53848232011-07-27 01:07:15 +00001680ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001681Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1682 if (!collection)
1683 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001684
Kaelyn Takata15867822014-11-21 18:48:04 +00001685 ExprResult result = CorrectDelayedTyposInExpr(collection);
1686 if (!result.isUsable())
1687 return ExprError();
1688 collection = result.get();
1689
John McCall53848232011-07-27 01:07:15 +00001690 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001691 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001692
1693 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001694 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001695 if (result.isInvalid())
1696 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001697 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001698
1699 // The operand needs to have object-pointer type.
1700 // TODO: should we do a contextual conversion?
1701 const ObjCObjectPointerType *pointerType =
1702 collection->getType()->getAs<ObjCObjectPointerType>();
1703 if (!pointerType)
1704 return Diag(forLoc, diag::err_collection_expr_type)
1705 << collection->getType() << collection->getSourceRange();
1706
1707 // Check that the operand provides
1708 // - countByEnumeratingWithState:objects:count:
1709 const ObjCObjectType *objectType = pointerType->getObjectType();
1710 ObjCInterfaceDecl *iface = objectType->getInterface();
1711
1712 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001713 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001714 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001715 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001716 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001717 ? diag::err_arc_collection_forward
1718 : 0,
1719 collection)) {
John McCall53848232011-07-27 01:07:15 +00001720 // Otherwise, if we have any useful type information, check that
1721 // the type declares the appropriate method.
1722 } else if (iface || !objectType->qual_empty()) {
1723 IdentifierInfo *selectorIdents[] = {
1724 &Context.Idents.get("countByEnumeratingWithState"),
1725 &Context.Idents.get("objects"),
1726 &Context.Idents.get("count")
1727 };
1728 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1729
Craig Topperc3ec1492014-05-26 06:22:03 +00001730 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001731
1732 // If there's an interface, look in both the public and private APIs.
1733 if (iface) {
1734 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001735 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001736 }
1737
1738 // Also check protocol qualifiers.
1739 if (!method)
1740 method = LookupMethodInQualifiedType(selector, pointerType,
1741 /*instance*/ true);
1742
1743 // If we didn't find it anywhere, give up.
1744 if (!method) {
1745 Diag(forLoc, diag::warn_collection_expr_type)
1746 << collection->getType() << selector << collection->getSourceRange();
1747 }
1748
1749 // TODO: check for an incompatible signature?
1750 }
1751
1752 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001753 return collection;
John McCall53848232011-07-27 01:07:15 +00001754}
1755
John McCalldadc5752010-08-24 06:29:42 +00001756StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001757Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001758 Stmt *First, Expr *collection,
1759 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001760
1761 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001762 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001763
Fariborz Jahanian93977672008-01-10 20:33:58 +00001764 if (First) {
1765 QualType FirstType;
1766 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001767 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001768 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1769 diag::err_toomany_element_decls));
1770
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001771 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1772 if (!D || D->isInvalidDecl())
1773 return StmtError();
1774
John McCall31168b02011-06-15 23:02:42 +00001775 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001776 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1777 // declare identifiers for objects having storage class 'auto' or
1778 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001779 if (!D->hasLocalStorage())
1780 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001781 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001782
1783 // If the type contained 'auto', deduce the 'auto' to 'id'.
1784 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001785 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1786 VK_RValue);
1787 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001788 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1789 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001790 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001791 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001792 D->setInvalidDecl();
1793 return StmtError();
1794 }
1795
Richard Smith061f1e22013-04-30 21:23:01 +00001796 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001797
1798 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001799 SourceLocation Loc =
1800 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001801 Diag(Loc, diag::warn_auto_var_is_id)
1802 << D->getDeclName();
1803 }
1804 }
1805
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001806 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001807 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001808 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001809 return StmtError(Diag(First->getLocStart(),
1810 diag::err_selector_element_not_lvalue)
1811 << First->getSourceRange());
1812
Mike Stump11289f42009-09-09 15:08:12 +00001813 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001814 if (FirstType.isConstQualified())
1815 Diag(ForLoc, diag::err_selector_element_const_type)
1816 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001817 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001818 if (!FirstType->isDependentType() &&
1819 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001820 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001821 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1822 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001823 }
Chad Rosier02a84392012-08-10 17:56:09 +00001824
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001825 if (CollectionExprResult.isInvalid())
1826 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001827
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001828 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001829 if (CollectionExprResult.isInvalid())
1830 return StmtError();
1831
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001832 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1833 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001834}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001835
Richard Smith02e85f32011-04-14 22:09:26 +00001836/// Finish building a variable declaration for a for-range statement.
1837/// \return true if an error occurs.
1838static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001839 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001840 // Deduce the type for the iterator variable now rather than leaving it to
1841 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001842 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001843 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001844 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001845 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001846 SemaRef.Diag(Loc, DiagID) << Init->getType();
1847 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001848 Decl->setInvalidDecl();
1849 return true;
1850 }
Richard Smith061f1e22013-04-30 21:23:01 +00001851 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001852
John McCall31168b02011-06-15 23:02:42 +00001853 // In ARC, infer lifetime.
1854 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1855 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001856 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001857 SemaRef.inferObjCARCLifetime(Decl))
1858 Decl->setInvalidDecl();
1859
Richard Smith02e85f32011-04-14 22:09:26 +00001860 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1861 /*TypeMayContainAuto=*/false);
1862 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001863 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001864 return false;
1865}
1866
Sam Panzer0f384432012-08-21 00:52:01 +00001867namespace {
1868
Richard Smith02e85f32011-04-14 22:09:26 +00001869/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001870/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001871/// nor from the diagnostics produced when analysing the implicit expressions
1872/// required in a for-range statement.
1873void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001874 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001875 CallExpr *CE = dyn_cast<CallExpr>(E);
1876 if (!CE)
1877 return;
1878 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1879 if (!D)
1880 return;
1881 SourceLocation Loc = D->getLocation();
1882
1883 std::string Description;
1884 bool IsTemplate = false;
1885 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1886 Description = SemaRef.getTemplateArgumentBindingsText(
1887 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1888 IsTemplate = true;
1889 }
1890
1891 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1892 << BEF << IsTemplate << Description << E->getType();
1893}
1894
Sam Panzer0f384432012-08-21 00:52:01 +00001895/// Build a variable declaration for a for-range statement.
1896VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1897 QualType Type, const char *Name) {
1898 DeclContext *DC = SemaRef.CurContext;
1899 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1900 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1901 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001902 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001903 Decl->setImplicit();
1904 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001905}
1906
1907}
1908
Fariborz Jahanian00213472012-07-06 19:04:04 +00001909static bool ObjCEnumerationCollection(Expr *Collection) {
1910 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001911 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001912}
1913
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001914/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001915///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001916/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001917/// A range-based for statement is equivalent to
1918///
1919/// {
1920/// auto && __range = range-init;
1921/// for ( auto __begin = begin-expr,
1922/// __end = end-expr;
1923/// __begin != __end;
1924/// ++__begin ) {
1925/// for-range-declaration = *__begin;
1926/// statement
1927/// }
1928/// }
1929///
1930/// The body of the loop is not available yet, since it cannot be analysed until
1931/// we have determined the type of the for-range-declaration.
1932StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001933Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001934 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001935 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001936 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001937 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001938
Richard Smith3249fed2013-08-21 01:40:36 +00001939 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001940 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001941
1942 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1943 assert(DS && "first part of for range not a decl stmt");
1944
1945 if (!DS->isSingleDecl()) {
1946 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1947 return StmtError();
1948 }
Richard Smith02e85f32011-04-14 22:09:26 +00001949
Richard Smith3249fed2013-08-21 01:40:36 +00001950 Decl *LoopVar = DS->getSingleDecl();
1951 if (LoopVar->isInvalidDecl() || !Range ||
1952 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1953 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001954 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001955 }
Richard Smith02e85f32011-04-14 22:09:26 +00001956
1957 // Build auto && __range = range-init
1958 SourceLocation RangeLoc = Range->getLocStart();
1959 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1960 Context.getAutoRRefDeductType(),
1961 "__range");
1962 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001963 diag::err_for_range_deduction_failure)) {
1964 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001965 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001966 }
Richard Smith02e85f32011-04-14 22:09:26 +00001967
1968 // Claim the type doesn't contain auto: we've already done the checking.
1969 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001970 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001971 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001972 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001973 if (RangeDecl.isInvalid()) {
1974 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001975 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001976 }
Richard Smith02e85f32011-04-14 22:09:26 +00001977
1978 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001979 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1980 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001981}
1982
1983/// \brief Create the initialization, compare, and increment steps for
1984/// the range-based for loop expression.
1985/// This function does not handle array-based for loops,
1986/// which are created in Sema::BuildCXXForRangeStmt.
1987///
1988/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1989/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1990/// CandidateSet and BEF are set and some non-success value is returned on
1991/// failure.
1992static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1993 Expr *BeginRange, Expr *EndRange,
1994 QualType RangeType,
1995 VarDecl *BeginVar,
1996 VarDecl *EndVar,
1997 SourceLocation ColonLoc,
1998 OverloadCandidateSet *CandidateSet,
1999 ExprResult *BeginExpr,
2000 ExprResult *EndExpr,
2001 Sema::BeginEndFunction *BEF) {
2002 DeclarationNameInfo BeginNameInfo(
2003 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2004 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2005 ColonLoc);
2006
2007 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2008 Sema::LookupMemberName);
2009 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2010
2011 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2012 // - if _RangeT is a class type, the unqualified-ids begin and end are
2013 // looked up in the scope of class _RangeT as if by class member access
2014 // lookup (3.4.5), and if either (or both) finds at least one
2015 // declaration, begin-expr and end-expr are __range.begin() and
2016 // __range.end(), respectively;
2017 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2018 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2019
2020 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2021 SourceLocation RangeLoc = BeginVar->getLocation();
2022 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2023
2024 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2025 << RangeLoc << BeginRange->getType() << *BEF;
2026 return Sema::FRS_DiagnosticIssued;
2027 }
2028 } else {
2029 // - otherwise, begin-expr and end-expr are begin(__range) and
2030 // end(__range), respectively, where begin and end are looked up with
2031 // argument-dependent lookup (3.4.2). For the purposes of this name
2032 // lookup, namespace std is an associated namespace.
2033
2034 }
2035
2036 *BEF = Sema::BEF_begin;
2037 Sema::ForRangeStatus RangeStatus =
2038 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2039 Sema::BEF_begin, BeginNameInfo,
2040 BeginMemberLookup, CandidateSet,
2041 BeginRange, BeginExpr);
2042
2043 if (RangeStatus != Sema::FRS_Success)
2044 return RangeStatus;
2045 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2046 diag::err_for_range_iter_deduction_failure)) {
2047 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2048 return Sema::FRS_DiagnosticIssued;
2049 }
2050
2051 *BEF = Sema::BEF_end;
2052 RangeStatus =
2053 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2054 Sema::BEF_end, EndNameInfo,
2055 EndMemberLookup, CandidateSet,
2056 EndRange, EndExpr);
2057 if (RangeStatus != Sema::FRS_Success)
2058 return RangeStatus;
2059 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2060 diag::err_for_range_iter_deduction_failure)) {
2061 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2062 return Sema::FRS_DiagnosticIssued;
2063 }
2064 return Sema::FRS_Success;
2065}
2066
2067/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002068/// If the attempt fails, this function will return a valid, null StmtResult
2069/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002070static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2071 SourceLocation ForLoc,
2072 Stmt *LoopVarDecl,
2073 SourceLocation ColonLoc,
2074 Expr *Range,
2075 SourceLocation RangeLoc,
2076 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002077 // Determine whether we can rebuild the for-range statement with a
2078 // dereferenced range expression.
2079 ExprResult AdjustedRange;
2080 {
2081 Sema::SFINAETrap Trap(SemaRef);
2082
2083 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2084 if (AdjustedRange.isInvalid())
2085 return StmtResult();
2086
2087 StmtResult SR =
2088 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2089 AdjustedRange.get(), RParenLoc,
2090 Sema::BFRK_Check);
2091 if (SR.isInvalid())
2092 return StmtResult();
2093 }
2094
2095 // The attempt to dereference worked well enough that it could produce a valid
2096 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2097 // case there are any other (non-fatal) problems with it.
2098 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2099 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2100 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2101 AdjustedRange.get(), RParenLoc,
2102 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002103}
2104
Richard Smith3249fed2013-08-21 01:40:36 +00002105namespace {
2106/// RAII object to automatically invalidate a declaration if an error occurs.
2107struct InvalidateOnErrorScope {
2108 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2109 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2110 ~InvalidateOnErrorScope() {
2111 if (Enabled && Trap.hasErrorOccurred())
2112 D->setInvalidDecl();
2113 }
2114
2115 DiagnosticErrorTrap Trap;
2116 Decl *D;
2117 bool Enabled;
2118};
2119}
2120
Richard Smitha05b3b52012-09-20 21:52:32 +00002121/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002122StmtResult
2123Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2124 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2125 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002126 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002127 Scope *S = getCurScope();
2128
2129 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2130 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2131 QualType RangeVarType = RangeVar->getType();
2132
2133 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2134 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2135
Richard Smith3249fed2013-08-21 01:40:36 +00002136 // If we hit any errors, mark the loop variable as invalid if its type
2137 // contains 'auto'.
2138 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2139 LoopVar->getType()->isUndeducedType());
2140
Richard Smith02e85f32011-04-14 22:09:26 +00002141 StmtResult BeginEndDecl = BeginEnd;
2142 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2143
Richard Smith27d807c2013-04-30 13:56:41 +00002144 if (RangeVarType->isDependentType()) {
2145 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002146 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002147
2148 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2149 // them in properly when we instantiate the loop.
2150 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2151 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2152 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002153 SourceLocation RangeLoc = RangeVar->getLocation();
2154
Ted Kremenekbed648e2011-10-10 22:36:28 +00002155 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2156
2157 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2158 VK_LValue, ColonLoc);
2159 if (BeginRangeRef.isInvalid())
2160 return StmtError();
2161
2162 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2163 VK_LValue, ColonLoc);
2164 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002165 return StmtError();
2166
2167 QualType AutoType = Context.getAutoDeductType();
2168 Expr *Range = RangeVar->getInit();
2169 if (!Range)
2170 return StmtError();
2171 QualType RangeType = Range->getType();
2172
2173 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002174 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002175 return StmtError();
2176
2177 // Build auto __begin = begin-expr, __end = end-expr.
2178 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2179 "__begin");
2180 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2181 "__end");
2182
2183 // Build begin-expr and end-expr and attach to __begin and __end variables.
2184 ExprResult BeginExpr, EndExpr;
2185 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2186 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2187 // __range + __bound, respectively, where __bound is the array bound. If
2188 // _RangeT is an array of unknown size or an array of incomplete type,
2189 // the program is ill-formed;
2190
2191 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002192 BeginExpr = BeginRangeRef;
2193 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002194 diag::err_for_range_iter_deduction_failure)) {
2195 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2196 return StmtError();
2197 }
2198
2199 // Find the array bound.
2200 ExprResult BoundExpr;
2201 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002202 BoundExpr = IntegerLiteral::Create(
2203 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002204 else if (const VariableArrayType *VAT =
2205 dyn_cast<VariableArrayType>(UnqAT))
2206 BoundExpr = VAT->getSizeExpr();
2207 else {
2208 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2209 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002210 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002211 }
2212
2213 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002214 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002215 BoundExpr.get());
2216 if (EndExpr.isInvalid())
2217 return StmtError();
2218 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2219 diag::err_for_range_iter_deduction_failure)) {
2220 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2221 return StmtError();
2222 }
2223 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002224 OverloadCandidateSet CandidateSet(RangeLoc,
2225 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002226 Sema::BeginEndFunction BEFFailure;
2227 ForRangeStatus RangeStatus =
2228 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2229 EndRangeRef.get(), RangeType,
2230 BeginVar, EndVar, ColonLoc, &CandidateSet,
2231 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002232
Richard Smitha05b3b52012-09-20 21:52:32 +00002233 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002234 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002235 // If the range is being built from an array parameter, emit a
2236 // a diagnostic that it is being treated as a pointer.
2237 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2238 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2239 QualType ArrayTy = PVD->getOriginalType();
2240 QualType PointerTy = PVD->getType();
2241 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2242 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2243 << RangeLoc << PVD << ArrayTy << PointerTy;
2244 Diag(PVD->getLocation(), diag::note_declared_at);
2245 return StmtError();
2246 }
2247 }
2248 }
2249
2250 // If building the range failed, try dereferencing the range expression
2251 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002252 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2253 LoopVarDecl, ColonLoc,
2254 Range, RangeLoc,
2255 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002256 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002257 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002258 }
2259
Sam Panzer0f384432012-08-21 00:52:01 +00002260 // Otherwise, emit diagnostics if we haven't already.
2261 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002262 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002263 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2264 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002266 }
2267 // Return an error if no fix was discovered.
2268 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002269 return StmtError();
2270 }
2271
Sam Panzer0f384432012-08-21 00:52:01 +00002272 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2273 "invalid range expression in for loop");
2274
2275 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002276 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2277 if (!Context.hasSameType(BeginType, EndType)) {
2278 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2279 << BeginType << EndType;
2280 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2281 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2282 }
2283
2284 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2285 // Claim the type doesn't contain auto: we've already done the checking.
2286 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002287 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002288 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002289 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2290
Ted Kremenekbed648e2011-10-10 22:36:28 +00002291 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2292 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002293 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002294 if (BeginRef.isInvalid())
2295 return StmtError();
2296
Richard Smith02e85f32011-04-14 22:09:26 +00002297 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2298 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002299 if (EndRef.isInvalid())
2300 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002301
2302 // Build and check __begin != __end expression.
2303 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2304 BeginRef.get(), EndRef.get());
2305 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2306 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2307 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002308 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2309 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002310 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2311 if (!Context.hasSameType(BeginType, EndType))
2312 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2313 return StmtError();
2314 }
2315
2316 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002317 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2318 VK_LValue, ColonLoc);
2319 if (BeginRef.isInvalid())
2320 return StmtError();
2321
Richard Smith02e85f32011-04-14 22:09:26 +00002322 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2323 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2324 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002325 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2326 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002327 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2328 return StmtError();
2329 }
2330
2331 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002332 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2333 VK_LValue, ColonLoc);
2334 if (BeginRef.isInvalid())
2335 return StmtError();
2336
Richard Smith02e85f32011-04-14 22:09:26 +00002337 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2338 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002339 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2340 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002341 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2342 return StmtError();
2343 }
2344
Richard Smitha05b3b52012-09-20 21:52:32 +00002345 // Attach *__begin as initializer for VD. Don't touch it if we're just
2346 // trying to determine whether this would be a valid range.
2347 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002348 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2349 /*TypeMayContainAuto=*/true);
2350 if (LoopVar->isInvalidDecl())
2351 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2352 }
2353 }
2354
Richard Smitha05b3b52012-09-20 21:52:32 +00002355 // Don't bother to actually allocate the result if we're just trying to
2356 // determine whether it would be valid.
2357 if (Kind == BFRK_Check)
2358 return StmtResult();
2359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002360 return new (Context) CXXForRangeStmt(
2361 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2362 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002363}
2364
Chad Rosier02a84392012-08-10 17:56:09 +00002365/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002366/// statement.
2367StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2368 if (!S || !B)
2369 return StmtError();
2370 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002371
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002372 ForStmt->setBody(B);
2373 return S;
2374}
2375
Richard Smith02e85f32011-04-14 22:09:26 +00002376/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2377/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2378/// body cannot be performed until after the type of the range variable is
2379/// determined.
2380StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2381 if (!S || !B)
2382 return StmtError();
2383
Fariborz Jahanian00213472012-07-06 19:04:04 +00002384 if (isa<ObjCForCollectionStmt>(S))
2385 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002386
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002387 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2388 ForStmt->setBody(B);
2389
2390 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2391 diag::warn_empty_range_based_for_body);
2392
Richard Smith02e85f32011-04-14 22:09:26 +00002393 return S;
2394}
2395
Chris Lattnercab02a62011-02-17 20:34:02 +00002396StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2397 SourceLocation LabelLoc,
2398 LabelDecl *TheDecl) {
2399 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002400 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002401 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002402}
Chris Lattner1c310502007-05-31 06:00:00 +00002403
John McCalldadc5752010-08-24 06:29:42 +00002404StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002405Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002406 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002407 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002408 if (!E->isTypeDependent()) {
2409 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002410 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002411 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002412 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002413 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2414 if (ExprRes.isInvalid())
2415 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002416 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002417 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002418 return StmtError();
2419 }
John McCalla95172b2010-08-01 00:26:45 +00002420
Richard Smith945f8d32013-01-14 22:39:08 +00002421 ExprResult ExprRes = ActOnFinishFullExpr(E);
2422 if (ExprRes.isInvalid())
2423 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002424 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002425
John McCallaab3e412010-08-25 08:40:02 +00002426 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002427
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002428 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002429}
2430
Nico Weberd64657f2015-03-09 02:47:59 +00002431static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2432 const Scope &DestScope) {
2433 if (!S.CurrentSEHFinally.empty() &&
2434 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2435 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2436 }
2437}
2438
John McCalldadc5752010-08-24 06:29:42 +00002439StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002440Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002441 Scope *S = CurScope->getContinueParent();
2442 if (!S) {
2443 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002444 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002445 }
Nico Weberd64657f2015-03-09 02:47:59 +00002446 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002447
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002448 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002449}
2450
John McCalldadc5752010-08-24 06:29:42 +00002451StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002452Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002453 Scope *S = CurScope->getBreakParent();
2454 if (!S) {
2455 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002456 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002457 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002458 if (S->isOpenMPLoopScope())
2459 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2460 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002461 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002462
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002463 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002464}
2465
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002466/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002467/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002468///
Douglas Gregor5d369002011-01-21 18:05:27 +00002469/// \param ReturnType If we're determining the copy elision candidate for
2470/// a return statement, this is the return type of the function. If we're
2471/// determining the copy elision candidate for a throw expression, this will
2472/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002473///
Douglas Gregor5d369002011-01-21 18:05:27 +00002474/// \param E The expression being returned from the function or block, or
2475/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002476///
Douglas Gregor86394412011-05-20 15:00:53 +00002477/// \param AllowFunctionParameter Whether we allow function parameters to
2478/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2479/// we re-use this logic to determine whether we should try to move as part of
2480/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002481///
2482/// \returns The NRVO candidate variable, if the return statement may use the
2483/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002484VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2485 Expr *E,
2486 bool AllowFunctionParameter) {
2487 if (!getLangOpts().CPlusPlus)
2488 return nullptr;
2489
2490 // - in a return statement in a function [where] ...
2491 // ... the expression is the name of a non-volatile automatic object ...
2492 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002493 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002494 return nullptr;
2495 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2496 if (!VD)
2497 return nullptr;
2498
2499 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2500 return VD;
2501 return nullptr;
2502}
2503
2504bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2505 bool AllowFunctionParameter) {
2506 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002507 // - in a return statement in a function with ...
2508 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002509 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002510 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002511 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002512 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002513 if (!VDType->isDependentType() &&
2514 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2515 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517
John McCall03318c12011-11-11 03:57:31 +00002518 // ...object (other than a function or catch-clause parameter)...
2519 if (VD->getKind() != Decl::Var &&
2520 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002521 return false;
2522 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002523
John McCall03318c12011-11-11 03:57:31 +00002524 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002525 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002526
2527 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002528 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002529
2530 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002531 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002532
2533 // Variables with higher required alignment than their type's ABI
2534 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002535 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002536 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002537 return false;
John McCall03318c12011-11-11 03:57:31 +00002538
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002539 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002540}
2541
Douglas Gregor626fbed2011-01-21 21:08:57 +00002542/// \brief Perform the initialization of a potentially-movable value, which
2543/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002544///
2545/// This routine implements C++0x [class.copy]p33, which attempts to treat
2546/// returned lvalues as rvalues in certain cases (to prefer move construction),
2547/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002549Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2550 const VarDecl *NRVOCandidate,
2551 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002552 Expr *Value,
2553 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002554 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555 // When the criteria for elision of a copy operation are met or would
2556 // be met save for the fact that the source object is a function
2557 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002558 // overload resolution to select the constructor for the copy is first
2559 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002560 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002561 if (AllowNRVO &&
2562 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002564 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
Douglas Gregorf282a762011-01-21 19:38:21 +00002566 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002568 = InitializationKind::CreateCopy(Value->getLocStart(),
2569 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002570 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002571
2572 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002573 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002574 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002575 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002576 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002577 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2578 StepEnd = Seq.step_end();
2579 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002580 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002581 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582
2583 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002584 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002585
Douglas Gregorf282a762011-01-21 19:38:21 +00002586 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002587 = Constructor->getParamDecl(0)->getType()
2588 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589
Douglas Gregorf282a762011-01-21 19:38:21 +00002590 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002591 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002592 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2593 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002594 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
Douglas Gregorf282a762011-01-21 19:38:21 +00002596 // Promote "AsRvalue" to the heap, since we now need this
2597 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002598 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600
Douglas Gregorf282a762011-01-21 19:38:21 +00002601 // Complete type-checking the initialization of the return type
2602 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002603 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002604 }
2605 }
2606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002607
Douglas Gregorf282a762011-01-21 19:38:21 +00002608 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002609 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002610 // (again) now with the return value expression as written.
2611 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002612 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002613
Douglas Gregorf282a762011-01-21 19:38:21 +00002614 return Res;
2615}
2616
Richard Smith4db51c22013-09-25 05:02:54 +00002617/// \brief Determine whether the declared return type of the specified function
2618/// contains 'auto'.
2619static bool hasDeducedReturnType(FunctionDecl *FD) {
2620 const FunctionProtoType *FPT =
2621 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002622 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002623}
2624
Eli Friedman34b49062012-01-26 03:00:14 +00002625/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2626/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002627///
John McCalldadc5752010-08-24 06:29:42 +00002628StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002629Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2630 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002631 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002632 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002633 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002634 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002635
Richard Smith4db51c22013-09-25 05:02:54 +00002636 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2637 // In C++1y, the return type may involve 'auto'.
2638 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2639 FunctionDecl *FD = CurLambda->CallOperator;
2640 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002641 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002642
2643 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2644 assert(AT && "lost auto type from lambda return type");
2645 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2646 FD->setInvalidDecl();
2647 return StmtError();
2648 }
Alp Toker314cc812014-01-25 16:55:45 +00002649 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002650 } else if (CurCap->HasImplicitReturnType) {
2651 // For blocks/lambdas with implicit return types, we check each return
2652 // statement individually, and deduce the common return type when the block
2653 // or lambda is completed.
2654 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002655 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002656 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2657 if (Result.isInvalid())
2658 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002659 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002660
Richard Smith5a0e50c2014-12-19 22:10:51 +00002661 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2662 // when deducing a return type for a lambda-expression (or by extension
2663 // for a block). These rules differ from the stated C++11 rules only in
2664 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002665 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002666 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002667 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002668 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002669 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002670 if (RetValExp) {
2671 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2672 // initializer list, because it is not an expression (even
2673 // though we represent it as one). We still deduce 'void'.
2674 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2675 << RetValExp->getSourceRange();
2676 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002677
Jordan Rosed39e5f12012-07-02 21:19:23 +00002678 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002679 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002680
2681 // Although we'll properly infer the type of the block once it's completed,
2682 // make sure we provide a return type now for better error recovery.
2683 if (CurCap->ReturnType.isNull())
2684 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002685 }
Eli Friedman34b49062012-01-26 03:00:14 +00002686 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002687
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002688 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002689 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2690 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2691 return StmtError();
2692 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002693 } else if (CapturedRegionScopeInfo *CurRegion =
2694 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2695 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2696 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002697 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002698 assert(CurLambda && "unknown kind of captured scope");
2699 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2700 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002701 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2702 return StmtError();
2703 }
2704 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002705
Steve Naroffc540d662008-09-03 18:15:37 +00002706 // Otherwise, verify that this result type matches the previous one. We are
2707 // pickier with blocks than for normal functions because we don't have GCC
2708 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002709 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002710 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002711 // Delay processing for now. TODO: there are lots of dependent
2712 // types we can conclusively prove aren't void.
2713 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002714 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002715 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002716 (RetValExp->isTypeDependent() ||
2717 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002718 if (!getLangOpts().CPlusPlus &&
2719 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002720 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002721 else {
2722 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002723 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002724 }
Steve Naroffc540d662008-09-03 18:15:37 +00002725 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002726 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002727 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2728 } else if (!RetValExp->isTypeDependent()) {
2729 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002730
John McCall5500ef22011-08-17 22:09:46 +00002731 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2732 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2733 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002734
John McCall5500ef22011-08-17 22:09:46 +00002735 // In C++ the return statement is handled via a copy initialization.
2736 // the C version of which boils down to CheckSingleAssignmentConstraints.
2737 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2738 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2739 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002740 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002741 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2742 FnRetType, RetValExp);
2743 if (Res.isInvalid()) {
2744 // FIXME: Cleanup temporaries here, anyway?
2745 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002746 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002747 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002748 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002749 } else {
2750 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002751 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002752
John McCall75f92b52011-08-17 21:34:14 +00002753 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002754 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2755 if (ER.isInvalid())
2756 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002757 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002758 }
John McCall5500ef22011-08-17 22:09:46 +00002759 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2760 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002761
Jordan Rosed39e5f12012-07-02 21:19:23 +00002762 // If we need to check for the named return value optimization,
2763 // or if we need to infer the return type,
2764 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002765 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002766 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002768 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002769}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002770
Nico Weber72889432014-09-06 01:25:55 +00002771namespace {
2772/// \brief Marks all typedefs in all local classes in a type referenced.
2773///
2774/// In a function like
2775/// auto f() {
2776/// struct S { typedef int a; };
2777/// return S();
2778/// }
2779///
2780/// the local type escapes and could be referenced in some TUs but not in
2781/// others. Pretend that all local typedefs are always referenced, to not warn
2782/// on this. This isn't necessary if f has internal linkage, or the typedef
2783/// is private.
2784class LocalTypedefNameReferencer
2785 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2786public:
2787 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2788 bool VisitRecordType(const RecordType *RT);
2789private:
2790 Sema &S;
2791};
2792bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2793 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2794 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2795 R->isDependentType())
2796 return true;
2797 for (auto *TmpD : R->decls())
2798 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2799 if (T->getAccess() != AS_private || R->hasFriends())
2800 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2801 return true;
2802}
2803}
2804
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002805TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002806 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002807 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2808 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002809 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002810}
2811
Richard Smith2a7d4812013-05-04 07:00:32 +00002812/// Deduce the return type for a function from a returned expression, per
2813/// C++1y [dcl.spec.auto]p6.
2814bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2815 SourceLocation ReturnLoc,
2816 Expr *&RetExpr,
2817 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002818 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002819 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002820
Richard Smithc58f38f2013-08-14 20:16:31 +00002821 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2822 // If the deduction is for a return statement and the initializer is
2823 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002824 Diag(RetExpr->getExprLoc(),
2825 getCurLambda() ? diag::err_lambda_return_init_list
2826 : diag::err_auto_fn_return_init_list)
2827 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002828 return true;
2829 }
2830
2831 if (FD->isDependentContext()) {
2832 // C++1y [dcl.spec.auto]p12:
2833 // Return type deduction [...] occurs when the definition is
2834 // instantiated even if the function body contains a return
2835 // statement with a non-type-dependent operand.
2836 assert(AT->isDeduced() && "should have deduced to dependent type");
2837 return false;
2838 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002839 // If the deduction is for a return statement and the initializer is
2840 // a braced-init-list, the program is ill-formed.
2841 if (isa<InitListExpr>(RetExpr)) {
2842 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2843 return true;
2844 }
2845
2846 // Otherwise, [...] deduce a value for U using the rules of template
2847 // argument deduction.
2848 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2849
2850 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2851 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2852 << OrigResultType.getType() << RetExpr->getType();
2853
2854 if (DAR != DAR_Succeeded)
2855 return true;
Nico Weber72889432014-09-06 01:25:55 +00002856
2857 // If a local type is part of the returned type, mark its fields as
2858 // referenced.
2859 LocalTypedefNameReferencer Referencer(*this);
2860 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002861 } else {
2862 // In the case of a return with no operand, the initializer is considered
2863 // to be void().
2864 //
2865 // Deduction here can only succeed if the return type is exactly 'cv auto'
2866 // or 'decltype(auto)', so just check for that case directly.
2867 if (!OrigResultType.getType()->getAs<AutoType>()) {
2868 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2869 << OrigResultType.getType();
2870 return true;
2871 }
2872 // We always deduce U = void in this case.
2873 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2874 if (Deduced.isNull())
2875 return true;
2876 }
2877
2878 // If a function with a declared return type that contains a placeholder type
2879 // has multiple return statements, the return type is deduced for each return
2880 // statement. [...] if the type deduced is not the same in each deduction,
2881 // the program is ill-formed.
2882 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2883 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002884 if (!FD->isDependentContext() &&
2885 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002886 const LambdaScopeInfo *LambdaSI = getCurLambda();
2887 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2888 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2889 << NewAT->getDeducedType() << AT->getDeducedType()
2890 << true /*IsLambda*/;
2891 } else {
2892 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2893 << (AT->isDecltypeAuto() ? 1 : 0)
2894 << NewAT->getDeducedType() << AT->getDeducedType();
2895 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002896 return true;
2897 }
2898 } else if (!FD->isInvalidDecl()) {
2899 // Update all declarations of the function to have the deduced return type.
2900 Context.adjustDeducedFunctionResultType(FD, Deduced);
2901 }
2902
2903 return false;
2904}
2905
John McCalldadc5752010-08-24 06:29:42 +00002906StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002907Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2908 Scope *CurScope) {
2909 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2910 if (R.isInvalid()) {
2911 return R;
2912 }
2913
2914 if (VarDecl *VD =
2915 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2916 CurScope->addNRVOCandidate(VD);
2917 } else {
2918 CurScope->setNoNRVO();
2919 }
2920
Nico Weberd64657f2015-03-09 02:47:59 +00002921 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
2922
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002923 return R;
2924}
2925
2926StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002927 // Check for unexpanded parameter packs.
2928 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2929 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002930
Eli Friedman34b49062012-01-26 03:00:14 +00002931 if (isa<CapturingScopeInfo>(getCurFunction()))
2932 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002933
Chris Lattner79413952008-12-04 23:50:19 +00002934 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002935 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002936 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002937 bool isObjCMethod = false;
2938
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002939 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002940 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002941 if (FD->hasAttrs())
2942 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002943 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002944 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002945 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002946 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002947 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002948 isObjCMethod = true;
2949 if (MD->hasAttrs())
2950 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002951 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2952 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002953 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002954 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002955 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2956 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002957 }
2958 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002959 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002960
Richard Smith2a7d4812013-05-04 07:00:32 +00002961 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2962 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002963 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002964 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2965 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002966 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002967 FD->setInvalidDecl();
2968 return StmtError();
2969 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002970 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 }
2972 }
2973 }
2974
Richard Smithc58f38f2013-08-14 20:16:31 +00002975 bool HasDependentReturnType = FnRetType->isDependentType();
2976
Craig Topperc3ec1492014-05-26 06:22:03 +00002977 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002978 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002979 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002980 if (isa<InitListExpr>(RetValExp)) {
2981 // We simply never allow init lists as the return value of void
2982 // functions. This is compatible because this was never allowed before,
2983 // so there's no legacy code to deal with.
2984 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2985 int FunctionKind = 0;
2986 if (isa<ObjCMethodDecl>(CurDecl))
2987 FunctionKind = 1;
2988 else if (isa<CXXConstructorDecl>(CurDecl))
2989 FunctionKind = 2;
2990 else if (isa<CXXDestructorDecl>(CurDecl))
2991 FunctionKind = 3;
2992
2993 Diag(ReturnLoc, diag::err_return_init_list)
2994 << CurDecl->getDeclName() << FunctionKind
2995 << RetValExp->getSourceRange();
2996
2997 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002998 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002999 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003000 // C99 6.8.6.4p1 (ext_ since GCC warns)
3001 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003002 if (RetValExp->getType()->isVoidType()) {
3003 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3004 if (isa<CXXConstructorDecl>(CurDecl) ||
3005 isa<CXXDestructorDecl>(CurDecl))
3006 D = diag::err_ctor_dtor_returns_void;
3007 else
3008 D = diag::ext_return_has_void_expr;
3009 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003010 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003011 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003012 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003013 if (Result.isInvalid())
3014 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003015 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003016 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003017 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003018 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003019 // return of void in constructor/destructor is illegal in C++.
3020 if (D == diag::err_ctor_dtor_returns_void) {
3021 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3022 Diag(ReturnLoc, D)
3023 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3024 << RetValExp->getSourceRange();
3025 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003026 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003027 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003028 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003029 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003030
3031 int FunctionKind = 0;
3032 if (isa<ObjCMethodDecl>(CurDecl))
3033 FunctionKind = 1;
3034 else if (isa<CXXConstructorDecl>(CurDecl))
3035 FunctionKind = 2;
3036 else if (isa<CXXDestructorDecl>(CurDecl))
3037 FunctionKind = 3;
3038
Nick Lewycky1be750a2011-06-01 07:44:31 +00003039 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003040 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003041 << RetValExp->getSourceRange();
3042 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003043 }
Mike Stump11289f42009-09-09 15:08:12 +00003044
Sebastian Redleef474c2012-02-22 10:50:08 +00003045 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003046 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3047 if (ER.isInvalid())
3048 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003049 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003050 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003052
Craig Topperc3ec1492014-05-26 06:22:03 +00003053 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003054 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003055 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003056
David Majnemer2887ad32014-12-13 08:12:56 +00003057 unsigned DiagID;
3058 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3059 // C++11 [stmt.return]p2
3060 DiagID = diag::err_constexpr_return_missing_expr;
3061 FD->setInvalidDecl();
3062 } else if (getLangOpts().C99) {
3063 // C99 6.8.6.4p1 (ext_ since GCC warns)
3064 DiagID = diag::ext_return_missing_expr;
3065 } else {
3066 // C90 6.6.6.4p4
3067 DiagID = diag::warn_return_missing_expr;
3068 }
3069
3070 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003071 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003072 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003073 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003074
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003075 Result = new (Context) ReturnStmt(ReturnLoc);
3076 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003077 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003078 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003079
3080 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3081
3082 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3083 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3084 // function return.
3085
3086 // In C++ the return statement is handled via a copy initialization,
3087 // the C version of which boils down to CheckSingleAssignmentConstraints.
3088 if (RetValExp)
3089 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003090 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003091 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003093 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003094 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003096 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003097 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003098 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003099 return StmtError();
3100 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003101 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003102
3103 // If we have a related result type, we need to implicitly
3104 // convert back to the formal result type. We can't pretend to
3105 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003106 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003107 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003108 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3109 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003110 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3111 if (Res.isInvalid()) {
3112 // FIXME: Clean up temporaries here anyway?
3113 return StmtError();
3114 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003115 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003116 }
3117
Artyom Skrobov9f213442014-01-24 11:10:39 +00003118 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3119 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121
John McCallacf0ee52010-10-08 02:01:28 +00003122 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003123 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3124 if (ER.isInvalid())
3125 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003126 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003127 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003128 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130
3131 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003132 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003133 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003134 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003135
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003136 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003137}
3138
John McCalldadc5752010-08-24 06:29:42 +00003139StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003140Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003141 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003142 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003143 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003144 if (Var && Var->isInvalidDecl())
3145 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003147 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003148}
3149
John McCalldadc5752010-08-24 06:29:42 +00003150StmtResult
John McCallb268a282010-08-23 23:25:46 +00003151Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003152 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003153}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003154
John McCalldadc5752010-08-24 06:29:42 +00003155StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003157 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003158 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003159 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3160
John McCallaab3e412010-08-25 08:40:02 +00003161 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003162 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003163 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3164 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003165}
3166
John McCall0bd3e402012-05-08 21:41:25 +00003167StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003168 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003169 ExprResult Result = DefaultLvalueConversion(Throw);
3170 if (Result.isInvalid())
3171 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003172
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003173 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003174 if (Result.isInvalid())
3175 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003176 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003177
Douglas Gregor2900c162010-04-22 21:44:01 +00003178 QualType ThrowType = Throw->getType();
3179 // Make sure the expression type is an ObjC pointer or "void *".
3180 if (!ThrowType->isDependentType() &&
3181 !ThrowType->isObjCObjectPointerType()) {
3182 const PointerType *PT = ThrowType->getAs<PointerType>();
3183 if (!PT || !PT->getPointeeType()->isVoidType())
3184 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3185 << Throw->getType() << Throw->getSourceRange());
3186 }
3187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003189 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003190}
3191
John McCalldadc5752010-08-24 06:29:42 +00003192StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003194 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003195 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003196 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3197
John McCallb268a282010-08-23 23:25:46 +00003198 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003199 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003200 // in the context of an @catch clause).
3201 Scope *AtCatchParent = CurScope;
3202 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3203 AtCatchParent = AtCatchParent->getParent();
3204 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003205 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 }
John McCallb268a282010-08-23 23:25:46 +00003207 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003208}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003209
John McCalld9bb7432011-07-27 21:50:02 +00003210ExprResult
3211Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3212 ExprResult result = DefaultLvalueConversion(operand);
3213 if (result.isInvalid())
3214 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003215 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003216
3217 // Make sure the expression type is an ObjC pointer or "void *".
3218 QualType type = operand->getType();
3219 if (!type->isDependentType() &&
3220 !type->isObjCObjectPointerType()) {
3221 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003222 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3223 if (getLangOpts().CPlusPlus) {
3224 if (RequireCompleteType(atLoc, type,
3225 diag::err_incomplete_receiver_type))
3226 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3227 << type << operand->getSourceRange();
3228
3229 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3230 if (!result.isUsable())
3231 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3232 << type << operand->getSourceRange();
3233
3234 operand = result.get();
3235 } else {
3236 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3237 << type << operand->getSourceRange();
3238 }
3239 }
John McCalld9bb7432011-07-27 21:50:02 +00003240 }
3241
3242 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003243 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003244}
3245
John McCalldadc5752010-08-24 06:29:42 +00003246StmtResult
John McCallb268a282010-08-23 23:25:46 +00003247Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3248 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003249 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003250 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003251 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003252}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003253
3254/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3255/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003256StmtResult
John McCall48871652010-08-21 09:40:31 +00003257Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003258 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003259 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003260 return new (Context)
3261 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003262}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003263
John McCall31168b02011-06-15 23:02:42 +00003264StmtResult
3265Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3266 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003267 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003268}
3269
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003270namespace {
Dan Gohman28ade552010-07-26 21:25:24 +00003271
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003272class TypeWithHandler {
3273 QualType t;
3274 CXXCatchStmt *stmt;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003275public:
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003276 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3277 : t(type), stmt(statement) {}
Sebastian Redl63c4da02009-07-29 17:15:45 +00003278
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003279 // An arbitrary order is fine as long as it places identical
3280 // types next to each other.
3281 bool operator<(const TypeWithHandler &y) const {
3282 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3283 return true;
3284 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003285 return false;
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003286 else
3287 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3288 }
3289
3290 bool operator==(const TypeWithHandler& other) const {
3291 return t == other.t;
3292 }
3293
3294 CXXCatchStmt *getCatchStmt() const { return stmt; }
3295 SourceLocation getTypeSpecStartLoc() const {
3296 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003297 }
3298};
3299
Dan Gohman28ade552010-07-26 21:25:24 +00003300}
3301
Sebastian Redl9b244a82008-12-22 21:35:02 +00003302/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3303/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003304StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3305 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003306 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003307 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003308 !getSourceManager().isInSystemHeader(TryLoc))
3309 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003310
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003311 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3312 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3313
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003314 sema::FunctionScopeInfo *FSI = getCurFunction();
3315
Reid Klecknere7175912015-02-02 22:15:31 +00003316 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003317 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003318 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003319 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003320 }
3321
Robert Wilhelmcafda822013-08-22 09:20:03 +00003322 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003323 assert(NumHandlers > 0 &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003324 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003325
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003326 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3327
Mike Stump11289f42009-09-09 15:08:12 +00003328 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003330 if (!Handler->getExceptionDecl()) {
3331 if (i < NumHandlers - 1)
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003332 return StmtError(Diag(Handler->getLocStart(),
3333 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003334
Sebastian Redl63c4da02009-07-29 17:15:45 +00003335 continue;
3336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003338 const QualType CaughtType = Handler->getCaughtType();
3339 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3340 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3341 }
3342
3343 // Detect handlers for the same type as an earlier one.
3344 if (NumHandlers > 1) {
3345 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3346
3347 TypeWithHandler prev = TypesWithHandlers[0];
3348 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3349 TypeWithHandler curr = TypesWithHandlers[i];
3350
3351 if (curr == prev) {
3352 Diag(curr.getTypeSpecStartLoc(),
3353 diag::warn_exception_caught_by_earlier_handler)
3354 << curr.getCatchStmt()->getCaughtType().getAsString();
3355 Diag(prev.getTypeSpecStartLoc(),
3356 diag::note_previous_exception_handler)
3357 << prev.getCatchStmt()->getCaughtType().getAsString();
3358 }
3359
3360 prev = curr;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003361 }
3362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003364 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003365
Aaron Ballman8a417bd2015-02-15 22:18:04 +00003366 // FIXME: We should detect handlers that cannot catch anything because an
3367 // earlier handler catches a superclass. Need to find a method that is not
3368 // quadratic for this.
3369 // Neither of these are explicitly forbidden, but every compiler detects them
3370 // and warns.
3371
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003372 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003373}
John Wiegley1c0675e2011-04-28 01:08:34 +00003374
Reid Klecknere7175912015-02-02 22:15:31 +00003375StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3376 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003377 assert(TryBlock && Handler);
3378
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003379 sema::FunctionScopeInfo *FSI = getCurFunction();
3380
Reid Klecknere7175912015-02-02 22:15:31 +00003381 // SEH __try is incompatible with C++ try. Borland appears to support this,
3382 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003383 if (!getLangOpts().Borland) {
3384 if (FSI->FirstCXXTryLoc.isValid()) {
3385 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3386 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3387 }
Reid Klecknere7175912015-02-02 22:15:31 +00003388 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003389
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003390 FSI->setHasSEHTry(TryLoc);
3391
3392 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3393 // track if they use SEH.
3394 DeclContext *DC = CurContext;
3395 while (DC && !DC->isFunctionOrMethod())
3396 DC = DC->getParent();
3397 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3398 if (FD)
3399 FD->setUsesSEHTry(true);
3400 else
3401 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003402
3403 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003404}
3405
3406StmtResult
3407Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3408 Expr *FilterExpr,
3409 Stmt *Block) {
3410 assert(FilterExpr && Block);
3411
3412 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003413 return StmtError(Diag(FilterExpr->getExprLoc(),
3414 diag::err_filter_expression_integral)
3415 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003416 }
3417
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003418 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003419}
3420
Nico Weberd64657f2015-03-09 02:47:59 +00003421void Sema::ActOnStartSEHFinallyBlock() {
3422 CurrentSEHFinally.push_back(CurScope);
3423}
3424
Nico Weberce903292015-03-09 03:17:15 +00003425void Sema::ActOnAbortSEHFinallyBlock() {
3426 CurrentSEHFinally.pop_back();
3427}
3428
Nico Weberd64657f2015-03-09 02:47:59 +00003429StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003430 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003431 CurrentSEHFinally.pop_back();
3432 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003433}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003434
Nico Weberc7d05962014-07-06 22:32:59 +00003435StmtResult
3436Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003437 Scope *SEHTryParent = CurScope;
3438 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3439 SEHTryParent = SEHTryParent->getParent();
3440 if (!SEHTryParent)
3441 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003442 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003443
Nico Weber9b982072014-07-07 00:12:30 +00003444 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003445}
3446
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003447StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3448 bool IsIfExists,
3449 NestedNameSpecifierLoc QualifierLoc,
3450 DeclarationNameInfo NameInfo,
3451 Stmt *Nested)
3452{
3453 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003454 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003455 cast<CompoundStmt>(Nested));
3456}
3457
3458
Chad Rosier02a84392012-08-10 17:56:09 +00003459StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003460 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003461 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003462 UnqualifiedId &Name,
3463 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003464 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003465 SS.getWithLocInContext(Context),
3466 GetNameFromUnqualifiedId(Name),
3467 Nested);
3468}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003469
3470RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003471Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3472 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003473 DeclContext *DC = CurContext;
3474 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3475 DC = DC->getParent();
3476
Craig Topperc3ec1492014-05-26 06:22:03 +00003477 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003478 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003479 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3480 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003481 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003482 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003483
Alexey Bataev330de032014-10-29 12:21:55 +00003484 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003485 DC->addDecl(RD);
3486 RD->setImplicit();
3487 RD->startDefinition();
3488
Alexey Bataev9959db52014-05-06 10:08:46 +00003489 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003490 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003491 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003492 return RD;
3493}
3494
3495static void buildCapturedStmtCaptureList(
3496 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3497 SmallVectorImpl<Expr *> &CaptureInits,
3498 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3499
3500 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3501 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3502
3503 if (Cap->isThisCapture()) {
3504 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3505 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003506 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003507 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003508 } else if (Cap->isVLATypeCapture()) {
3509 Captures.push_back(
3510 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3511 CaptureInits.push_back(nullptr);
3512 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003513 }
3514
3515 assert(Cap->isReferenceCapture() &&
3516 "non-reference capture not yet implemented");
3517
3518 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3519 CapturedStmt::VCK_ByRef,
3520 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003521 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003522 }
3523}
3524
3525void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003526 CapturedRegionKind Kind,
3527 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003528 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003529 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003530
Alexey Bataev9959db52014-05-06 10:08:46 +00003531 // Build the context parameter
3532 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3533 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3534 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3535 ImplicitParamDecl *Param
3536 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3537 DC->addDecl(Param);
3538
3539 CD->setContextParam(0, Param);
3540
3541 // Enter the capturing scope for this captured region.
3542 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3543
3544 if (CurScope)
3545 PushDeclContext(CurScope, CD);
3546 else
3547 CurContext = CD;
3548
3549 PushExpressionEvaluationContext(PotentiallyEvaluated);
3550}
3551
3552void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3553 CapturedRegionKind Kind,
3554 ArrayRef<CapturedParamNameType> Params) {
3555 CapturedDecl *CD = nullptr;
3556 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3557
3558 // Build the context parameter
3559 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3560 bool ContextIsFound = false;
3561 unsigned ParamNum = 0;
3562 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3563 E = Params.end();
3564 I != E; ++I, ++ParamNum) {
3565 if (I->second.isNull()) {
3566 assert(!ContextIsFound &&
3567 "null type has been found already for '__context' parameter");
3568 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3569 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3570 ImplicitParamDecl *Param
3571 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3572 DC->addDecl(Param);
3573 CD->setContextParam(ParamNum, Param);
3574 ContextIsFound = true;
3575 } else {
3576 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3577 ImplicitParamDecl *Param
3578 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3579 DC->addDecl(Param);
3580 CD->setParam(ParamNum, Param);
3581 }
3582 }
3583 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003584 if (!ContextIsFound) {
3585 // Add __context implicitly if it is not specified.
3586 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3587 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3588 ImplicitParamDecl *Param =
3589 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3590 DC->addDecl(Param);
3591 CD->setContextParam(ParamNum, Param);
3592 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003593 // Enter the capturing scope for this captured region.
3594 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3595
3596 if (CurScope)
3597 PushDeclContext(CurScope, CD);
3598 else
3599 CurContext = CD;
3600
3601 PushExpressionEvaluationContext(PotentiallyEvaluated);
3602}
3603
Wei Pan17fbf6e2013-05-04 03:59:06 +00003604void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003605 DiscardCleanupsInEvaluationContext();
3606 PopExpressionEvaluationContext();
3607
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003608 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3609 RecordDecl *Record = RSI->TheRecordDecl;
3610 Record->setInvalidDecl();
3611
Aaron Ballman62e47c42014-03-10 13:43:55 +00003612 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003613 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3614 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003615
Wei Pan17fbf6e2013-05-04 03:59:06 +00003616 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003617 PopFunctionScopeInfo();
3618}
3619
3620StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3621 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3622
3623 SmallVector<CapturedStmt::Capture, 4> Captures;
3624 SmallVector<Expr *, 4> CaptureInits;
3625 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3626
3627 CapturedDecl *CD = RSI->TheCapturedDecl;
3628 RecordDecl *RD = RSI->TheRecordDecl;
3629
Wei Pan17fbf6e2013-05-04 03:59:06 +00003630 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3631 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003632 CaptureInits, CD, RD);
3633
3634 CD->setBody(Res->getCapturedStmt());
3635 RD->completeDefinition();
3636
Wei Pan17fbf6e2013-05-04 03:59:06 +00003637 DiscardCleanupsInEvaluationContext();
3638 PopExpressionEvaluationContext();
3639
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003640 PopDeclContext();
3641 PopFunctionScopeInfo();
3642
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003643 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003644}