blob: 8d5bec80a125143ef6bb950dc12ef0f40f473e51 [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"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
293 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
294 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
295 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000296 }
John McCall2351cb92010-04-06 22:24:14 +0000297 // Diagnose "(void*) blah" as a typo for "(void) blah".
298 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
299 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
300 QualType T = TI->getType();
301
302 // We really do want to use the non-canonical type here.
303 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000304 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000305
306 Diag(Loc, diag::warn_unused_voidptr)
307 << FixItHint::CreateRemoval(TL.getStarLoc());
308 return;
309 }
310 }
311
Eli Friedmanc11535c2012-05-24 00:47:05 +0000312 if (E->isGLValue() && E->getType().isVolatileQualified()) {
313 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
314 return;
315 }
316
Craig Topperc3ec1492014-05-26 06:22:03 +0000317 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000318}
319
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000320void Sema::ActOnStartOfCompoundStmt() {
321 PushCompoundScope();
322}
323
324void Sema::ActOnFinishOfCompoundStmt() {
325 PopCompoundScope();
326}
327
328sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
329 return getCurFunction()->CompoundScopes.back();
330}
331
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000332StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
333 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
334 const unsigned NumElts = Elts.size();
335
Chris Lattnerd864daf2007-08-27 04:29:41 +0000336 // If we're in C89 mode, check that we don't have any decls after stmts. If
337 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 // Note that __extension__ can be around a decl.
340 unsigned i = 0;
341 // Skip over all declarations.
342 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
343 /*empty*/;
344
345 // We found the end of the list or a statement. Scan for another declstmt.
346 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
347 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerd864daf2007-08-27 04:29:41 +0000349 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000350 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000351 Diag(D->getLocation(), diag::ext_mixed_decls_code);
352 }
353 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000354 // Warn about unused expressions in statements.
355 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000356 // Ignore statements that are last in a statement expression.
357 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000358 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000360 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000361 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000362
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000363 // Check for suspicious empty body (null statement) in `for' and `while'
364 // statements. Don't do anything for template instantiations, this just adds
365 // noise.
366 if (NumElts != 0 && !CurrentInstantiationScope &&
367 getCurCompoundScope().HasEmptyLoopBodies) {
368 for (unsigned i = 0; i != NumElts - 1; ++i)
369 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
370 }
371
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000372 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000373}
374
John McCalldadc5752010-08-24 06:29:42 +0000375StmtResult
John McCallb268a282010-08-23 23:25:46 +0000376Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
377 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000378 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000379 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000380
John McCallaab3e412010-08-25 08:40:02 +0000381 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000382 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000383 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000384 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000385
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000386 ExprResult LHS =
387 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
388 if (!getLangOpts().CPlusPlus11)
389 return VerifyIntegerConstantExpression(E);
390 if (Expr *CondExpr =
391 getCurFunction()->SwitchStack.back()->getCond()) {
392 QualType CondType = CondExpr->getType();
393 llvm::APSInt TempVal;
394 return CheckConvertedConstantExpression(E, CondType, TempVal,
395 CCEK_CaseValue);
396 }
397 return ExprError();
398 });
399 if (LHS.isInvalid())
400 return StmtError();
401 LHSVal = LHS.get();
402
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000403 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000404 // C99 6.8.4.2p3: The expression shall be an integer constant.
405 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000406 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000407 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000408 if (!LHSVal)
409 return StmtError();
410 }
Richard Smithf8379a02012-01-18 23:55:52 +0000411
412 // GCC extension: The expression shall be an integer constant.
413
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000415 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000416 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000417 }
418 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000419
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000420 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000421 getLangOpts().CPlusPlus11);
422 if (LHS.isInvalid())
423 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000424
Richard Smith5b555da2014-11-20 01:24:12 +0000425 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
426 getLangOpts().CPlusPlus11)
427 : ExprResult();
428 if (RHS.isInvalid())
429 return StmtError();
430
431 CaseStmt *CS = new (Context)
432 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000433 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000434 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000435}
436
Chris Lattner34a22092009-03-04 04:23:07 +0000437/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000438void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000439 DiagnoseUnusedExprResult(SubStmt);
440
Chris Lattner34a22092009-03-04 04:23:07 +0000441 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000442 CS->setSubStmt(SubStmt);
443}
444
John McCalldadc5752010-08-24 06:29:42 +0000445StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000446Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000447 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000448 DiagnoseUnusedExprResult(SubStmt);
449
John McCallaab3e412010-08-25 08:40:02 +0000450 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000451 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000452 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000453 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000454
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000455 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000456 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000458}
459
John McCalldadc5752010-08-24 06:29:42 +0000460StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000461Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
462 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000463 // If the label was multiply defined, reject it now.
464 if (TheDecl->getStmt()) {
465 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
466 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000467 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000468 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000469
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000470 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000471 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
472 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000473 if (!TheDecl->isGnuLocal()) {
474 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000475 if (!TheDecl->isMSAsmLabel()) {
476 // Don't update the location of MS ASM labels. These will result in
477 // a diagnostic, and changing the location here will mess that up.
478 TheDecl->setLocation(IdentLoc);
479 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000480 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000481 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000482}
483
Richard Smithc202b282012-04-14 00:33:13 +0000484StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000485 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000486 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000487 // Fill in the declaration and return it.
488 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000489 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000490}
491
Richard Trieufaca2d82016-02-18 23:58:40 +0000492namespace {
493class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
494 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
495 Sema &SemaRef;
496public:
497 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
498 void VisitBinaryOperator(BinaryOperator *E) {
499 if (E->getOpcode() == BO_Comma)
500 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
501 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
502 }
503};
504}
505
John McCalldadc5752010-08-24 06:29:42 +0000506StmtResult
Richard Smith03a4aa32016-06-23 19:02:52 +0000507Sema::ActOnIfStmt(SourceLocation IfLoc, ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000508 Stmt *thenStmt, SourceLocation ElseLoc,
509 Stmt *elseStmt) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000510 auto CondVal = Cond.get();
511 if (Cond.isInvalid()) {
512 CondVal.first = nullptr;
513 CondVal.second = new (Context)
514 OpaqueValueExpr(SourceLocation(), Context.BoolTy, VK_RValue);
Anders Carlssondb83d772007-10-10 20:50:11 +0000515 }
516
Richard Smith03a4aa32016-06-23 19:02:52 +0000517 if (!Diags.isIgnored(diag::warn_comma_operator,
518 CondVal.second->getExprLoc()))
519 CommaVisitor(*this).Visit(CondVal.second);
520
521 DiagnoseUnusedExprResult(thenStmt);
522
523 if (!elseStmt) {
524 DiagnoseEmptyStmtBody(CondVal.second->getLocEnd(), thenStmt,
525 diag::warn_empty_if_body);
526 }
527
528 DiagnoseUnusedExprResult(elseStmt);
529
530 return new (Context) IfStmt(Context, IfLoc, CondVal.first, CondVal.second,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000531 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000532}
Steve Naroff86272ea2007-05-29 02:14:17 +0000533
Chris Lattner67998452007-08-23 18:29:20 +0000534namespace {
535 struct CaseCompareFunctor {
536 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
537 const llvm::APSInt &RHS) {
538 return LHS.first < RHS;
539 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000540 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
541 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
542 return LHS.first < RHS.first;
543 }
Chris Lattner67998452007-08-23 18:29:20 +0000544 bool operator()(const llvm::APSInt &LHS,
545 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
546 return LHS < RHS.first;
547 }
548 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000549}
Chris Lattner67998452007-08-23 18:29:20 +0000550
Chris Lattner4b2ff022007-09-21 18:15:22 +0000551/// CmpCaseVals - Comparison predicate for sorting case values.
552///
553static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
554 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
555 if (lhs.first < rhs.first)
556 return true;
557
558 if (lhs.first == rhs.first &&
559 lhs.second->getCaseLoc().getRawEncoding()
560 < rhs.second->getCaseLoc().getRawEncoding())
561 return true;
562 return false;
563}
564
Douglas Gregorbd6839732010-02-08 22:24:16 +0000565/// CmpEnumVals - Comparison predicate for sorting enumeration values.
566///
567static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
568 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
569{
570 return lhs.first < rhs.first;
571}
572
573/// EqEnumVals - Comparison preficate for uniqing enumeration values.
574///
575static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
576 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
577{
578 return lhs.first == rhs.first;
579}
580
Chris Lattnera96d4272009-10-16 16:45:22 +0000581/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
582/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000583static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
584 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
585 expr = cleanups->getSubExpr();
586 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
587 if (impcast->getCastKind() != CK_IntegralCast) break;
588 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000589 }
590 return expr->getType();
591}
592
Richard Smith03a4aa32016-06-23 19:02:52 +0000593ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000594 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
595 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000596
Douglas Gregore2b37442012-05-04 22:38:52 +0000597 public:
598 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000599 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
600 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000601
Craig Toppere14c0f82014-03-12 04:55:44 +0000602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
603 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000604 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
605 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000606
Craig Toppere14c0f82014-03-12 04:55:44 +0000607 SemaDiagnosticBuilder diagnoseIncomplete(
608 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000609 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
610 << T << Cond->getSourceRange();
611 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Craig Toppere14c0f82014-03-12 04:55:44 +0000613 SemaDiagnosticBuilder diagnoseExplicitConv(
614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000615 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
616 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000617
Craig Toppere14c0f82014-03-12 04:55:44 +0000618 SemaDiagnosticBuilder noteExplicitConv(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
622 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
625 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder noteAmbiguous(
630 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
632 << ConvTy->isEnumeralType() << ConvTy;
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder diagnoseConversion(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000637 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000638 }
639 } SwitchDiagnoser(Cond);
640
Richard Smith03a4aa32016-06-23 19:02:52 +0000641 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000642 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000643 if (CondResult.isInvalid())
644 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645
John McCall5939b162011-08-06 07:30:58 +0000646 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000647 return UsualUnaryConversions(CondResult.get());
648}
John McCall5939b162011-08-06 07:30:58 +0000649
Richard Smith03a4aa32016-06-23 19:02:52 +0000650StmtResult
651Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, ConditionResult Cond) {
652 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000653 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000654
John McCallaab3e412010-08-25 08:40:02 +0000655 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Richard Smith03a4aa32016-06-23 19:02:52 +0000657 SwitchStmt *SS =
658 new (Context) SwitchStmt(Context, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000659 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000660 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000661}
662
Gabor Greif16e02862010-10-01 22:05:14 +0000663static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000664 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000665 Val.setIsSigned(IsSigned);
666}
667
Richard Smith077d0832014-08-04 00:40:48 +0000668/// Check the specified case value is in range for the given unpromoted switch
669/// type.
670static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
671 unsigned UnpromotedWidth, bool UnpromotedSign) {
672 // If the case value was signed and negative and the switch expression is
673 // unsigned, don't bother to warn: this is implementation-defined behavior.
674 // FIXME: Introduce a second, default-ignored warning for this case?
675 if (UnpromotedWidth < Val.getBitWidth()) {
676 llvm::APSInt ConvVal(Val);
677 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
678 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
679 // FIXME: Use different diagnostics for overflow in conversion to promoted
680 // type versus "switch expression cannot have this value". Use proper
681 // IntRange checking rather than just looking at the unpromoted type here.
682 if (ConvVal != Val)
683 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
684 << ConvVal.toString(10);
685 }
686}
687
Alexis Hunt724f14e2014-11-28 00:53:20 +0000688typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
689
Dmitri Gribenko58683752013-12-05 22:52:07 +0000690/// Returns true if we should emit a diagnostic about this case expression not
691/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000692static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000693 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000694 const Expr *CaseExpr,
695 EnumValsTy::iterator &EI,
696 EnumValsTy::iterator &EIEnd,
697 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000698 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
Richard Smith332653c2015-09-04 01:03:03 +0000709 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000710 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);
Richard Trieucc3949d2016-02-18 22:34:54 +0000977 --i;
978 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 continue;
980 }
John McCalld3dfbd62010-05-18 03:19:21 +0000981
982 if (ShouldCheckConstantCond &&
983 LoVal <= ConstantCondValue &&
984 ConstantCondValue <= HiVal)
985 ShouldCheckConstantCond = false;
986
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 HiVals.push_back(HiVal);
988 }
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000990 // Rescan the ranges, looking for overlap with singleton values and other
991 // ranges. Since the range list is sorted, we only need to compare case
992 // ranges with their neighbors.
993 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
994 llvm::APSInt &CRLo = CaseRanges[i].first;
995 llvm::APSInt &CRHi = HiVals[i];
996 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000997
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000998 // Check to see whether the case range overlaps with any
999 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001000 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001001 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 // Find the smallest value >= the lower bound. If I is in the
1004 // case range, then we have overlap.
1005 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1006 CaseVals.end(), CRLo,
1007 CaseCompareFunctor());
1008 if (I != CaseVals.end() && I->first < CRHi) {
1009 OverlapVal = I->first; // Found overlap with scalar.
1010 OverlapStmt = I->second;
1011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001013 // Find the smallest value bigger than the upper bound.
1014 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1015 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1016 OverlapVal = (I-1)->first; // Found overlap with scalar.
1017 OverlapStmt = (I-1)->second;
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001020 // Check to see if this case stmt overlaps with the subsequent
1021 // case range.
1022 if (i && CRLo <= HiVals[i-1]) {
1023 OverlapVal = HiVals[i-1]; // Found overlap with range.
1024 OverlapStmt = CaseRanges[i-1].second;
1025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001027 if (OverlapStmt) {
1028 // If we have a duplicate, report it.
1029 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1030 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001031 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001032 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001033 // FIXME: We really want to remove the bogus case stmt from the
1034 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001035 CaseListIsErroneous = true;
1036 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001037 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001038 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001039
John McCalld3dfbd62010-05-18 03:19:21 +00001040 // Complain if we have a constant condition and we didn't find a match.
1041 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1042 // TODO: it would be nice if we printed enums as enums, chars as
1043 // chars, etc.
1044 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1045 << ConstantCondValue.toString(10)
1046 << CondExpr->getSourceRange();
1047 }
1048
1049 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001050 // values. We only issue a warning if there is not 'default:', but
1051 // we still do the analysis to preserve this information in the AST
1052 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001053 //
Chris Lattner51679082010-09-16 17:09:42 +00001054 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001055
Douglas Gregorbd6839732010-02-08 22:24:16 +00001056 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001057 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001058 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001059 EnumValsTy EnumVals;
1060
John McCalld3dfbd62010-05-18 03:19:21 +00001061 // Gather all enum values, set their type and sort them,
1062 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001063 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001064 llvm::APSInt Val = EDI->getInitVal();
1065 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001066 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001067 }
1068 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001069 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001070 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001071
1072 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001073 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001074 CI != CaseVals.end(); CI++) {
1075 Expr *CaseExpr = CI->second->getLHS();
1076 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1077 CI->first))
1078 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1079 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001080 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001081
David Blaikiee476f972012-01-22 02:31:55 +00001082 // See which of case ranges aren't in enum
1083 EI = EnumVals.begin();
1084 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001085 RI != CaseRanges.end(); RI++) {
1086 Expr *CaseExpr = RI->second->getLHS();
1087 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1088 RI->first))
1089 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1090 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001091
Chad Rosier02a84392012-08-10 17:56:09 +00001092 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001093 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1094 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001095
1096 CaseExpr = RI->second->getRHS();
1097 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1098 Hi))
1099 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1100 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102
Ted Kremenekc42f3452010-09-09 00:05:53 +00001103 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001104 auto CI = CaseVals.begin();
1105 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001106 bool hasCasesNotInSwitch = false;
1107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001108 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001109
Alexis Hunt724f14e2014-11-28 00:53:20 +00001110 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001111 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001112 while (CI != CaseVals.end() && CI->first < EI->first)
1113 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001114
Douglas Gregorbd6839732010-02-08 22:24:16 +00001115 if (CI != CaseVals.end() && CI->first == EI->first)
1116 continue;
1117
Ted Kremenekc42f3452010-09-09 00:05:53 +00001118 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001119 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001120 llvm::APSInt Hi =
1121 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001122 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001123 if (EI->first <= Hi)
1124 break;
1125 }
1126
Ted Kremenekc42f3452010-09-09 00:05:53 +00001127 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001128 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001129 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001130 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
David Blaikie60ac6382012-01-23 04:46:12 +00001133 if (TheDefaultStmt && UnhandledNames.empty())
1134 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001135
Chris Lattner51679082010-09-16 17:09:42 +00001136 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001137 if (!UnhandledNames.empty()) {
1138 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1139 TheDefaultStmt ? diag::warn_def_missing_case
1140 : diag::warn_missing_case)
1141 << (int)UnhandledNames.size();
1142
1143 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1144 I != E; ++I)
1145 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001146 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001147
1148 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001149 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001150 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001151 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001152
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001153 if (BodyStmt)
1154 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1155 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001156
Mike Stump87c57ac2009-05-16 07:39:55 +00001157 // FIXME: If the case list was broken is some way, we don't have a good system
1158 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001159 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001160 return StmtError();
1161
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001162 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001163}
1164
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001165void
1166Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1167 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001168 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001169 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001170
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001171 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001172 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001173 SrcType->isIntegerType()) {
1174 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1175 SrcExpr->isIntegerConstantExpr(Context)) {
1176 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001177 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001178 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1179
1180 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001181 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001182 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001183
Alexis Hunt724f14e2014-11-28 00:53:20 +00001184 if (ED->hasAttr<FlagEnumAttr>()) {
1185 if (!IsValueInFlagEnum(ED, RhsVal, true))
1186 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001187 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001188 } else {
1189 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1190 EnumValsTy;
1191 EnumValsTy EnumVals;
1192
1193 // Gather all enum values, set their type and sort them,
1194 // allowing easier comparison with rhs constant.
1195 for (auto *EDI : ED->enumerators()) {
1196 llvm::APSInt Val = EDI->getInitVal();
1197 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1198 EnumVals.push_back(std::make_pair(Val, EDI));
1199 }
1200 if (EnumVals.empty())
1201 return;
1202 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1203 EnumValsTy::iterator EIend =
1204 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1205
1206 // See which values aren't in the enum.
1207 EnumValsTy::const_iterator EI = EnumVals.begin();
1208 while (EI != EIend && EI->first < RhsVal)
1209 EI++;
1210 if (EI == EIend || EI->first != RhsVal) {
1211 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1212 << DstType.getUnqualifiedType();
1213 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001214 }
1215 }
1216 }
1217}
1218
Richard Smith03a4aa32016-06-23 19:02:52 +00001219StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1220 Stmt *Body) {
1221 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001222 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Richard Smith03a4aa32016-06-23 19:02:52 +00001224 auto CondVal = Cond.get();
1225 CheckBreakContinueBinding(CondVal.second);
1226
1227 if (CondVal.second &&
1228 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1229 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001230
John McCallb268a282010-08-23 23:25:46 +00001231 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001233 if (isa<NullStmt>(Body))
1234 getCurCompoundScope().setHasEmptyLoopBodies();
1235
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001236 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001237 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001238}
1239
John McCalldadc5752010-08-24 06:29:42 +00001240StmtResult
John McCallb268a282010-08-23 23:25:46 +00001241Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001242 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001243 Expr *Cond, SourceLocation CondRParen) {
1244 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001245
Serge Pavlov09f99242014-01-23 15:05:00 +00001246 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001247 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001248 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001249 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001250 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001251
Richard Smith945f8d32013-01-14 22:39:08 +00001252 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001253 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001254 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001255 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001256
John McCallb268a282010-08-23 23:25:46 +00001257 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001258
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001259 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001260}
1261
Richard Trieu451a5db2012-04-30 18:01:30 +00001262namespace {
1263 // This visitor will traverse a conditional statement and store all
1264 // the evaluated decls into a vector. Simple is set to true if none
1265 // of the excluded constructs are used.
1266 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001267 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001268 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001269 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001270 public:
1271 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001272
Craig Topper4dd9b432014-08-17 23:49:53 +00001273 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001274 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001275 Inherited(S.Context),
1276 Decls(Decls),
1277 Ranges(Ranges),
1278 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001279
Richard Trieu9d228802013-05-31 22:46:45 +00001280 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001281
Richard Trieu9d228802013-05-31 22:46:45 +00001282 // Replaces the method in EvaluatedExprVisitor.
1283 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001284 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001285 }
1286
1287 // Any Stmt not whitelisted will cause the condition to be marked complex.
1288 void VisitStmt(Stmt *S) {
1289 Simple = false;
1290 }
1291
1292 void VisitBinaryOperator(BinaryOperator *E) {
1293 Visit(E->getLHS());
1294 Visit(E->getRHS());
1295 }
1296
1297 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001298 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001299 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001300
Richard Trieu9d228802013-05-31 22:46:45 +00001301 void VisitUnaryOperator(UnaryOperator *E) {
1302 // Skip checking conditionals with derefernces.
1303 if (E->getOpcode() == UO_Deref)
1304 Simple = false;
1305 else
1306 Visit(E->getSubExpr());
1307 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001308
Richard Trieu9d228802013-05-31 22:46:45 +00001309 void VisitConditionalOperator(ConditionalOperator *E) {
1310 Visit(E->getCond());
1311 Visit(E->getTrueExpr());
1312 Visit(E->getFalseExpr());
1313 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001314
Richard Trieu9d228802013-05-31 22:46:45 +00001315 void VisitParenExpr(ParenExpr *E) {
1316 Visit(E->getSubExpr());
1317 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001318
Richard Trieu9d228802013-05-31 22:46:45 +00001319 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1320 Visit(E->getOpaqueValue()->getSourceExpr());
1321 Visit(E->getFalseExpr());
1322 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001323
Richard Trieu9d228802013-05-31 22:46:45 +00001324 void VisitIntegerLiteral(IntegerLiteral *E) { }
1325 void VisitFloatingLiteral(FloatingLiteral *E) { }
1326 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1327 void VisitCharacterLiteral(CharacterLiteral *E) { }
1328 void VisitGNUNullExpr(GNUNullExpr *E) { }
1329 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 void VisitDeclRefExpr(DeclRefExpr *E) {
1332 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1333 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001334
Richard Trieu9d228802013-05-31 22:46:45 +00001335 Ranges.push_back(E->getSourceRange());
1336
1337 Decls.insert(VD);
1338 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001339
1340 }; // end class DeclExtractor
1341
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001342 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001343 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001344 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001345 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001346 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001347
Richard Trieu9d228802013-05-31 22:46:45 +00001348 public:
1349 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001350
Craig Topper4dd9b432014-08-17 23:49:53 +00001351 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001352 Stmt *Statement) :
1353 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1354 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001355
Richard Trieu9d228802013-05-31 22:46:45 +00001356 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001357 }
1358
Richard Trieu9d228802013-05-31 22:46:45 +00001359 void VisitReturnStmt(ReturnStmt *S) {
1360 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001361 }
1362
Richard Trieu9d228802013-05-31 22:46:45 +00001363 void VisitBreakStmt(BreakStmt *S) {
1364 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001365 }
1366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 void VisitGotoStmt(GotoStmt *S) {
1368 FoundDecl = true;
1369 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001370
Richard Trieu9d228802013-05-31 22:46:45 +00001371 void VisitCastExpr(CastExpr *E) {
1372 if (E->getCastKind() == CK_LValueToRValue)
1373 CheckLValueToRValueCast(E->getSubExpr());
1374 else
1375 Visit(E->getSubExpr());
1376 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void CheckLValueToRValueCast(Expr *E) {
1379 E = E->IgnoreParenImpCasts();
1380
1381 if (isa<DeclRefExpr>(E)) {
1382 return;
1383 }
1384
1385 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1386 Visit(CO->getCond());
1387 CheckLValueToRValueCast(CO->getTrueExpr());
1388 CheckLValueToRValueCast(CO->getFalseExpr());
1389 return;
1390 }
1391
1392 if (BinaryConditionalOperator *BCO =
1393 dyn_cast<BinaryConditionalOperator>(E)) {
1394 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1395 CheckLValueToRValueCast(BCO->getFalseExpr());
1396 return;
1397 }
1398
1399 Visit(E);
1400 }
1401
1402 void VisitDeclRefExpr(DeclRefExpr *E) {
1403 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1404 if (Decls.count(VD))
1405 FoundDecl = true;
1406 }
1407
Steven Wu92910f62016-03-10 02:02:48 +00001408 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1409 // Only need to visit the semantics for POE.
1410 // SyntaticForm doesn't really use the Decal.
1411 for (auto *S : POE->semantics()) {
1412 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1413 // Look past the OVE into the expression it binds.
1414 Visit(OVE->getSourceExpr());
1415 else
1416 Visit(S);
1417 }
1418 }
1419
Richard Trieu9d228802013-05-31 22:46:45 +00001420 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001421
1422 }; // end class DeclMatcher
1423
1424 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1425 Expr *Third, Stmt *Body) {
1426 // Condition is empty
1427 if (!Second) return;
1428
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001429 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1430 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001431 return;
1432
1433 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1434 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001435 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001436 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001437 DE.Visit(Second);
1438
1439 // Don't analyze complex conditionals.
1440 if (!DE.isSimple()) return;
1441
1442 // No decls found.
1443 if (Decls.size() == 0) return;
1444
Richard Trieu0030f1d2012-05-04 03:01:54 +00001445 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001446 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1447 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001448 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001449 if ((*I)->getType().isVolatileQualified() ||
1450 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001451
1452 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1453 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1454 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1455 return;
1456
1457 // Load decl names into diagnostic.
1458 if (Decls.size() > 4)
1459 PDiag << 0;
1460 else {
1461 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001462 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1463 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001464 I != E; ++I)
1465 PDiag << (*I)->getDeclName();
1466 }
1467
1468 // Load SourceRanges into diagnostic if there is room.
1469 // Otherwise, load the SourceRange of the conditional expression.
1470 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001471 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001472 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001473 I != E; ++I)
1474 PDiag << *I;
1475 else
1476 PDiag << Second->getSourceRange();
1477
1478 S.Diag(Ranges.begin()->getBegin(), PDiag);
1479 }
1480
Richard Trieu4e7c9622013-08-06 21:31:54 +00001481 // If Statement is an incemement or decrement, return true and sets the
1482 // variables Increment and DRE.
1483 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1484 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001485 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1486 if (!Cleanups->cleanupsHaveSideEffects())
1487 Statement = Cleanups->getSubExpr();
1488
Richard Trieu4e7c9622013-08-06 21:31:54 +00001489 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1490 switch (UO->getOpcode()) {
1491 default: return false;
1492 case UO_PostInc:
1493 case UO_PreInc:
1494 Increment = true;
1495 break;
1496 case UO_PostDec:
1497 case UO_PreDec:
1498 Increment = false;
1499 break;
1500 }
1501 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1502 return DRE;
1503 }
1504
1505 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1506 FunctionDecl *FD = Call->getDirectCallee();
1507 if (!FD || !FD->isOverloadedOperator()) return false;
1508 switch (FD->getOverloadedOperator()) {
1509 default: return false;
1510 case OO_PlusPlus:
1511 Increment = true;
1512 break;
1513 case OO_MinusMinus:
1514 Increment = false;
1515 break;
1516 }
1517 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1518 return DRE;
1519 }
1520
1521 return false;
1522 }
1523
Serge Pavlov09f99242014-01-23 15:05:00 +00001524 // A visitor to determine if a continue or break statement is a
1525 // subexpression.
1526 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1527 SourceLocation BreakLoc;
1528 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001529 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001530 BreakContinueFinder(Sema &S, Stmt* Body) :
1531 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001532 Visit(Body);
1533 }
1534
Serge Pavlov09f99242014-01-23 15:05:00 +00001535 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001536
1537 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001538 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001539 }
1540
Serge Pavlov09f99242014-01-23 15:05:00 +00001541 void VisitBreakStmt(BreakStmt* E) {
1542 BreakLoc = E->getBreakLoc();
1543 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001544
Serge Pavlov09f99242014-01-23 15:05:00 +00001545 bool ContinueFound() { return ContinueLoc.isValid(); }
1546 bool BreakFound() { return BreakLoc.isValid(); }
1547 SourceLocation GetContinueLoc() { return ContinueLoc; }
1548 SourceLocation GetBreakLoc() { return BreakLoc; }
1549
1550 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001551
1552 // Emit a warning when a loop increment/decrement appears twice per loop
1553 // iteration. The conditions which trigger this warning are:
1554 // 1) The last statement in the loop body and the third expression in the
1555 // for loop are both increment or both decrement of the same variable
1556 // 2) No continue statements in the loop body.
1557 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1558 // Return when there is nothing to check.
1559 if (!Body || !Third) return;
1560
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001561 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1562 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001563 return;
1564
1565 // Get the last statement from the loop body.
1566 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1567 if (!CS || CS->body_empty()) return;
1568 Stmt *LastStmt = CS->body_back();
1569 if (!LastStmt) return;
1570
1571 bool LoopIncrement, LastIncrement;
1572 DeclRefExpr *LoopDRE, *LastDRE;
1573
1574 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1575 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1576
1577 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001578 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001579 if (LoopIncrement != LastIncrement ||
1580 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1581
Serge Pavlov09f99242014-01-23 15:05:00 +00001582 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001583
1584 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1585 << LastDRE->getDecl() << LastIncrement;
1586 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1587 << LoopIncrement;
1588 }
1589
Richard Trieu451a5db2012-04-30 18:01:30 +00001590} // end namespace
1591
Serge Pavlov09f99242014-01-23 15:05:00 +00001592
1593void Sema::CheckBreakContinueBinding(Expr *E) {
1594 if (!E || getLangOpts().CPlusPlus)
1595 return;
1596 BreakContinueFinder BCFinder(*this, E);
1597 Scope *BreakParent = CurScope->getBreakParent();
1598 if (BCFinder.BreakFound() && BreakParent) {
1599 if (BreakParent->getFlags() & Scope::SwitchScope) {
1600 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1601 } else {
1602 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1603 << "break";
1604 }
1605 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1606 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1607 << "continue";
1608 }
1609}
1610
Richard Smith03a4aa32016-06-23 19:02:52 +00001611StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1612 Stmt *First, ConditionResult Second,
1613 FullExprArg third, SourceLocation RParenLoc,
1614 Stmt *Body) {
1615 if (Second.isInvalid())
1616 return StmtError();
1617
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
Richard Smith03a4aa32016-06-23 19:02:52 +00001635 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001636 CheckBreakContinueBinding(third.get());
1637
Richard Smith03a4aa32016-06-23 19:02:52 +00001638 if (!Second.get().first)
1639 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1640 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001641 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001642
Richard Smith03a4aa32016-06-23 19:02:52 +00001643 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001644 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001645 Second.get().second->getExprLoc()))
1646 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001647
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001648 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649
Anders Carlsson1682af52009-08-01 01:39:59 +00001650 DiagnoseUnusedExprResult(First);
1651 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001652 DiagnoseUnusedExprResult(Body);
1653
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001654 if (isa<NullStmt>(Body))
1655 getCurCompoundScope().setHasEmptyLoopBodies();
1656
Richard Smith03a4aa32016-06-23 19:02:52 +00001657 return new (Context)
1658 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1659 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001660}
1661
John McCall34376a62010-12-04 03:47:34 +00001662/// In an Objective C collection iteration statement:
1663/// for (x in y)
1664/// x can be an arbitrary l-value expression. Bind it up as a
1665/// full-expression.
1666StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001667 // Reduce placeholder expressions here. Note that this rejects the
1668 // use of pseudo-object l-values in this position.
1669 ExprResult result = CheckPlaceholderExpr(E);
1670 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001671 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001672
Richard Smith945f8d32013-01-14 22:39:08 +00001673 ExprResult FullExpr = ActOnFinishFullExpr(E);
1674 if (FullExpr.isInvalid())
1675 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001676 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001677}
1678
John McCall53848232011-07-27 01:07:15 +00001679ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001680Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1681 if (!collection)
1682 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001683
Kaelyn Takata15867822014-11-21 18:48:04 +00001684 ExprResult result = CorrectDelayedTyposInExpr(collection);
1685 if (!result.isUsable())
1686 return ExprError();
1687 collection = result.get();
1688
John McCall53848232011-07-27 01:07:15 +00001689 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001690 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001691
1692 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001693 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001694 if (result.isInvalid())
1695 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001696 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001697
1698 // The operand needs to have object-pointer type.
1699 // TODO: should we do a contextual conversion?
1700 const ObjCObjectPointerType *pointerType =
1701 collection->getType()->getAs<ObjCObjectPointerType>();
1702 if (!pointerType)
1703 return Diag(forLoc, diag::err_collection_expr_type)
1704 << collection->getType() << collection->getSourceRange();
1705
1706 // Check that the operand provides
1707 // - countByEnumeratingWithState:objects:count:
1708 const ObjCObjectType *objectType = pointerType->getObjectType();
1709 ObjCInterfaceDecl *iface = objectType->getInterface();
1710
1711 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001712 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001713 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001714 (getLangOpts().ObjCAutoRefCount
1715 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1716 diag::err_arc_collection_forward, collection)
1717 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001718 // Otherwise, if we have any useful type information, check that
1719 // the type declares the appropriate method.
1720 } else if (iface || !objectType->qual_empty()) {
1721 IdentifierInfo *selectorIdents[] = {
1722 &Context.Idents.get("countByEnumeratingWithState"),
1723 &Context.Idents.get("objects"),
1724 &Context.Idents.get("count")
1725 };
1726 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1727
Craig Topperc3ec1492014-05-26 06:22:03 +00001728 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001729
1730 // If there's an interface, look in both the public and private APIs.
1731 if (iface) {
1732 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001733 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001734 }
1735
1736 // Also check protocol qualifiers.
1737 if (!method)
1738 method = LookupMethodInQualifiedType(selector, pointerType,
1739 /*instance*/ true);
1740
1741 // If we didn't find it anywhere, give up.
1742 if (!method) {
1743 Diag(forLoc, diag::warn_collection_expr_type)
1744 << collection->getType() << selector << collection->getSourceRange();
1745 }
1746
1747 // TODO: check for an incompatible signature?
1748 }
1749
1750 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001751 return collection;
John McCall53848232011-07-27 01:07:15 +00001752}
1753
John McCalldadc5752010-08-24 06:29:42 +00001754StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001755Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001756 Stmt *First, Expr *collection,
1757 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001758
1759 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001760 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001761
Fariborz Jahanian93977672008-01-10 20:33:58 +00001762 if (First) {
1763 QualType FirstType;
1764 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001765 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001766 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1767 diag::err_toomany_element_decls));
1768
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001769 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1770 if (!D || D->isInvalidDecl())
1771 return StmtError();
1772
John McCall31168b02011-06-15 23:02:42 +00001773 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001774 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1775 // declare identifiers for objects having storage class 'auto' or
1776 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001777 if (!D->hasLocalStorage())
1778 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001779 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001780
1781 // If the type contained 'auto', deduce the 'auto' to 'id'.
1782 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001783 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1784 VK_RValue);
1785 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001786 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1787 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001788 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001789 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001790 D->setInvalidDecl();
1791 return StmtError();
1792 }
1793
Richard Smith061f1e22013-04-30 21:23:01 +00001794 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001795
1796 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001797 SourceLocation Loc =
1798 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001799 Diag(Loc, diag::warn_auto_var_is_id)
1800 << D->getDeclName();
1801 }
1802 }
1803
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001804 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001805 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001806 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001807 return StmtError(Diag(First->getLocStart(),
1808 diag::err_selector_element_not_lvalue)
1809 << First->getSourceRange());
1810
Mike Stump11289f42009-09-09 15:08:12 +00001811 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001812 if (FirstType.isConstQualified())
1813 Diag(ForLoc, diag::err_selector_element_const_type)
1814 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001815 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001816 if (!FirstType->isDependentType() &&
1817 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001818 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001819 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1820 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001821 }
Chad Rosier02a84392012-08-10 17:56:09 +00001822
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001823 if (CollectionExprResult.isInvalid())
1824 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001825
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001826 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001827 if (CollectionExprResult.isInvalid())
1828 return StmtError();
1829
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001830 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1831 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001832}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001833
Richard Smith02e85f32011-04-14 22:09:26 +00001834/// Finish building a variable declaration for a for-range statement.
1835/// \return true if an error occurs.
1836static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001837 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001838 if (Decl->getType()->isUndeducedType()) {
1839 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1840 if (!Res.isUsable()) {
1841 Decl->setInvalidDecl();
1842 return true;
1843 }
1844 Init = Res.get();
1845 }
1846
Richard Smith02e85f32011-04-14 22:09:26 +00001847 // Deduce the type for the iterator variable now rather than leaving it to
1848 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001849 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001850 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001851 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001852 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001853 SemaRef.Diag(Loc, DiagID) << Init->getType();
1854 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001855 Decl->setInvalidDecl();
1856 return true;
1857 }
Richard Smith061f1e22013-04-30 21:23:01 +00001858 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001859
John McCall31168b02011-06-15 23:02:42 +00001860 // In ARC, infer lifetime.
1861 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1862 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001863 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001864 SemaRef.inferObjCARCLifetime(Decl))
1865 Decl->setInvalidDecl();
1866
Richard Smith02e85f32011-04-14 22:09:26 +00001867 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1868 /*TypeMayContainAuto=*/false);
1869 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001870 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001871 return false;
1872}
1873
Sam Panzer0f384432012-08-21 00:52:01 +00001874namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001875// An enum to represent whether something is dealing with a call to begin()
1876// or a call to end() in a range-based for loop.
1877enum BeginEndFunction {
1878 BEF_begin,
1879 BEF_end
1880};
Sam Panzer0f384432012-08-21 00:52:01 +00001881
Richard Smith02e85f32011-04-14 22:09:26 +00001882/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001883/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001884/// nor from the diagnostics produced when analysing the implicit expressions
1885/// required in a for-range statement.
1886void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001887 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001888 CallExpr *CE = dyn_cast<CallExpr>(E);
1889 if (!CE)
1890 return;
1891 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1892 if (!D)
1893 return;
1894 SourceLocation Loc = D->getLocation();
1895
1896 std::string Description;
1897 bool IsTemplate = false;
1898 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1899 Description = SemaRef.getTemplateArgumentBindingsText(
1900 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1901 IsTemplate = true;
1902 }
1903
1904 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1905 << BEF << IsTemplate << Description << E->getType();
1906}
1907
Sam Panzer0f384432012-08-21 00:52:01 +00001908/// Build a variable declaration for a for-range statement.
1909VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1910 QualType Type, const char *Name) {
1911 DeclContext *DC = SemaRef.CurContext;
1912 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1913 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1914 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001915 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001916 Decl->setImplicit();
1917 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001918}
1919
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001920}
Richard Smith02e85f32011-04-14 22:09:26 +00001921
Fariborz Jahanian00213472012-07-06 19:04:04 +00001922static bool ObjCEnumerationCollection(Expr *Collection) {
1923 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001925}
1926
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001927/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001928///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001929/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001930/// A range-based for statement is equivalent to
1931///
1932/// {
1933/// auto && __range = range-init;
1934/// for ( auto __begin = begin-expr,
1935/// __end = end-expr;
1936/// __begin != __end;
1937/// ++__begin ) {
1938/// for-range-declaration = *__begin;
1939/// statement
1940/// }
1941/// }
1942///
1943/// The body of the loop is not available yet, since it cannot be analysed until
1944/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001945StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1946 SourceLocation CoawaitLoc, Stmt *First,
1947 SourceLocation ColonLoc, Expr *Range,
1948 SourceLocation RParenLoc,
1949 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001950 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001951 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001952
Richard Smith3249fed2013-08-21 01:40:36 +00001953 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001954 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001955
1956 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1957 assert(DS && "first part of for range not a decl stmt");
1958
1959 if (!DS->isSingleDecl()) {
1960 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1961 return StmtError();
1962 }
Richard Smith02e85f32011-04-14 22:09:26 +00001963
Richard Smith3249fed2013-08-21 01:40:36 +00001964 Decl *LoopVar = DS->getSingleDecl();
1965 if (LoopVar->isInvalidDecl() || !Range ||
1966 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1967 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001968 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001969 }
Richard Smith02e85f32011-04-14 22:09:26 +00001970
Richard Smithcfd53b42015-10-22 06:13:50 +00001971 // Coroutines: 'for co_await' implicitly co_awaits its range.
1972 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001973 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00001974 if (Coawait.isInvalid()) return StmtError();
1975 Range = Coawait.get();
1976 }
1977
Richard Smith02e85f32011-04-14 22:09:26 +00001978 // Build auto && __range = range-init
1979 SourceLocation RangeLoc = Range->getLocStart();
1980 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1981 Context.getAutoRRefDeductType(),
1982 "__range");
1983 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001984 diag::err_for_range_deduction_failure)) {
1985 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001986 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001987 }
Richard Smith02e85f32011-04-14 22:09:26 +00001988
1989 // Claim the type doesn't contain auto: we've already done the checking.
1990 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001991 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001992 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001993 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001994 if (RangeDecl.isInvalid()) {
1995 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001996 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001997 }
Richard Smith02e85f32011-04-14 22:09:26 +00001998
Richard Smithcfd53b42015-10-22 06:13:50 +00001999 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002000 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2001 /*Cond=*/nullptr, /*Inc=*/nullptr,
2002 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002003}
2004
2005/// \brief Create the initialization, compare, and increment steps for
2006/// the range-based for loop expression.
2007/// This function does not handle array-based for loops,
2008/// which are created in Sema::BuildCXXForRangeStmt.
2009///
2010/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2011/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2012/// CandidateSet and BEF are set and some non-success value is returned on
2013/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002014static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002015 Expr *BeginRange, Expr *EndRange,
2016 QualType RangeType,
2017 VarDecl *BeginVar,
2018 VarDecl *EndVar,
2019 SourceLocation ColonLoc,
2020 OverloadCandidateSet *CandidateSet,
2021 ExprResult *BeginExpr,
2022 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002023 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002024 DeclarationNameInfo BeginNameInfo(
2025 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2026 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2027 ColonLoc);
2028
2029 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2030 Sema::LookupMemberName);
2031 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2032
2033 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2034 // - if _RangeT is a class type, the unqualified-ids begin and end are
2035 // looked up in the scope of class _RangeT as if by class member access
2036 // lookup (3.4.5), and if either (or both) finds at least one
2037 // declaration, begin-expr and end-expr are __range.begin() and
2038 // __range.end(), respectively;
2039 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2040 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2041
2042 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2043 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002044 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002045
2046 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2047 << RangeLoc << BeginRange->getType() << *BEF;
2048 return Sema::FRS_DiagnosticIssued;
2049 }
2050 } else {
2051 // - otherwise, begin-expr and end-expr are begin(__range) and
2052 // end(__range), respectively, where begin and end are looked up with
2053 // argument-dependent lookup (3.4.2). For the purposes of this name
2054 // lookup, namespace std is an associated namespace.
2055
2056 }
2057
Richard Smith9f690bd2015-10-27 06:02:45 +00002058 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002059 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002060 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002061 BeginMemberLookup, CandidateSet,
2062 BeginRange, BeginExpr);
2063
Richard Smith9f690bd2015-10-27 06:02:45 +00002064 if (RangeStatus != Sema::FRS_Success) {
2065 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2066 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2067 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002068 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002069 }
Sam Panzer0f384432012-08-21 00:52:01 +00002070 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2071 diag::err_for_range_iter_deduction_failure)) {
2072 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2073 return Sema::FRS_DiagnosticIssued;
2074 }
2075
Richard Smith9f690bd2015-10-27 06:02:45 +00002076 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002077 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002078 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002079 EndMemberLookup, CandidateSet,
2080 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002081 if (RangeStatus != Sema::FRS_Success) {
2082 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2083 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2084 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002085 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002086 }
Sam Panzer0f384432012-08-21 00:52:01 +00002087 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2088 diag::err_for_range_iter_deduction_failure)) {
2089 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2090 return Sema::FRS_DiagnosticIssued;
2091 }
2092 return Sema::FRS_Success;
2093}
2094
2095/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002096/// If the attempt fails, this function will return a valid, null StmtResult
2097/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002098static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2099 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002100 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002101 Stmt *LoopVarDecl,
2102 SourceLocation ColonLoc,
2103 Expr *Range,
2104 SourceLocation RangeLoc,
2105 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002106 // Determine whether we can rebuild the for-range statement with a
2107 // dereferenced range expression.
2108 ExprResult AdjustedRange;
2109 {
2110 Sema::SFINAETrap Trap(SemaRef);
2111
2112 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2113 if (AdjustedRange.isInvalid())
2114 return StmtResult();
2115
Richard Smith9f690bd2015-10-27 06:02:45 +00002116 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2117 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2118 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002119 if (SR.isInvalid())
2120 return StmtResult();
2121 }
2122
2123 // The attempt to dereference worked well enough that it could produce a valid
2124 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2125 // case there are any other (non-fatal) problems with it.
2126 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2127 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002128 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2129 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002130 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002131}
2132
Richard Smith3249fed2013-08-21 01:40:36 +00002133namespace {
2134/// RAII object to automatically invalidate a declaration if an error occurs.
2135struct InvalidateOnErrorScope {
2136 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2137 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2138 ~InvalidateOnErrorScope() {
2139 if (Enabled && Trap.hasErrorOccurred())
2140 D->setInvalidDecl();
2141 }
2142
2143 DiagnosticErrorTrap Trap;
2144 Decl *D;
2145 bool Enabled;
2146};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002147}
Richard Smith3249fed2013-08-21 01:40:36 +00002148
Richard Smitha05b3b52012-09-20 21:52:32 +00002149/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002150StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002151Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002152 SourceLocation ColonLoc, Stmt *RangeDecl,
2153 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002154 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002155 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002156 // FIXME: This should not be used during template instantiation. We should
2157 // pick up the set of unqualified lookup results for the != and + operators
2158 // in the initial parse.
2159 //
2160 // Testcase (accepts-invalid):
2161 // template<typename T> void f() { for (auto x : T()) {} }
2162 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2163 // bool operator!=(N::X, N::X); void operator++(N::X);
2164 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002165 Scope *S = getCurScope();
2166
2167 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2168 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2169 QualType RangeVarType = RangeVar->getType();
2170
2171 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2172 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2173
Richard Smith3249fed2013-08-21 01:40:36 +00002174 // If we hit any errors, mark the loop variable as invalid if its type
2175 // contains 'auto'.
2176 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2177 LoopVar->getType()->isUndeducedType());
2178
Richard Smith01694c32016-03-20 10:33:40 +00002179 StmtResult BeginDeclStmt = Begin;
2180 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002181 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2182
Richard Smith27d807c2013-04-30 13:56:41 +00002183 if (RangeVarType->isDependentType()) {
2184 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002185 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002186
2187 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2188 // them in properly when we instantiate the loop.
2189 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2190 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002191 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002192 SourceLocation RangeLoc = RangeVar->getLocation();
2193
Ted Kremenekbed648e2011-10-10 22:36:28 +00002194 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2195
2196 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2197 VK_LValue, ColonLoc);
2198 if (BeginRangeRef.isInvalid())
2199 return StmtError();
2200
2201 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2202 VK_LValue, ColonLoc);
2203 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002204 return StmtError();
2205
2206 QualType AutoType = Context.getAutoDeductType();
2207 Expr *Range = RangeVar->getInit();
2208 if (!Range)
2209 return StmtError();
2210 QualType RangeType = Range->getType();
2211
2212 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002213 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002214 return StmtError();
2215
2216 // Build auto __begin = begin-expr, __end = end-expr.
2217 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2218 "__begin");
2219 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2220 "__end");
2221
2222 // Build begin-expr and end-expr and attach to __begin and __end variables.
2223 ExprResult BeginExpr, EndExpr;
2224 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2225 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2226 // __range + __bound, respectively, where __bound is the array bound. If
2227 // _RangeT is an array of unknown size or an array of incomplete type,
2228 // the program is ill-formed;
2229
2230 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002231 BeginExpr = BeginRangeRef;
2232 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002233 diag::err_for_range_iter_deduction_failure)) {
2234 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2235 return StmtError();
2236 }
2237
2238 // Find the array bound.
2239 ExprResult BoundExpr;
2240 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002241 BoundExpr = IntegerLiteral::Create(
2242 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002243 else if (const VariableArrayType *VAT =
2244 dyn_cast<VariableArrayType>(UnqAT))
2245 BoundExpr = VAT->getSizeExpr();
2246 else {
2247 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2248 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002249 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002250 }
2251
2252 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002253 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002254 BoundExpr.get());
2255 if (EndExpr.isInvalid())
2256 return StmtError();
2257 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2258 diag::err_for_range_iter_deduction_failure)) {
2259 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2260 return StmtError();
2261 }
2262 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002263 OverloadCandidateSet CandidateSet(RangeLoc,
2264 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002265 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002266 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002267 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002268 EndRangeRef.get(), RangeType,
2269 BeginVar, EndVar, ColonLoc, &CandidateSet,
2270 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002271
Richard Smitha05b3b52012-09-20 21:52:32 +00002272 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002273 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002274 // If the range is being built from an array parameter, emit a
2275 // a diagnostic that it is being treated as a pointer.
2276 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2277 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2278 QualType ArrayTy = PVD->getOriginalType();
2279 QualType PointerTy = PVD->getType();
2280 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2281 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2282 << RangeLoc << PVD << ArrayTy << PointerTy;
2283 Diag(PVD->getLocation(), diag::note_declared_at);
2284 return StmtError();
2285 }
2286 }
2287 }
2288
2289 // If building the range failed, try dereferencing the range expression
2290 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002291 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002292 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002293 LoopVarDecl, ColonLoc,
2294 Range, RangeLoc,
2295 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002296 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002297 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002298 }
2299
Sam Panzer0f384432012-08-21 00:52:01 +00002300 // Otherwise, emit diagnostics if we haven't already.
2301 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002302 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002303 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2304 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002305 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002306 }
2307 // Return an error if no fix was discovered.
2308 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002309 return StmtError();
2310 }
2311
Sam Panzer0f384432012-08-21 00:52:01 +00002312 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2313 "invalid range expression in for loop");
2314
2315 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002316 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002317 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2318 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002319 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2320 ? diag::warn_for_range_begin_end_types_differ
2321 : diag::ext_for_range_begin_end_types_differ)
2322 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002323 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2324 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2325 }
2326
Richard Smith01694c32016-03-20 10:33:40 +00002327 BeginDeclStmt =
2328 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2329 EndDeclStmt =
2330 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002331
Ted Kremenekbed648e2011-10-10 22:36:28 +00002332 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2333 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002334 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002335 if (BeginRef.isInvalid())
2336 return StmtError();
2337
Richard Smith02e85f32011-04-14 22:09:26 +00002338 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2339 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002340 if (EndRef.isInvalid())
2341 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002342
2343 // Build and check __begin != __end expression.
2344 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2345 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002346 if (!NotEqExpr.isInvalid())
2347 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2348 if (!NotEqExpr.isInvalid())
2349 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002350 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002351 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2352 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002353 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2354 if (!Context.hasSameType(BeginType, EndType))
2355 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2356 return StmtError();
2357 }
2358
2359 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002360 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2361 VK_LValue, ColonLoc);
2362 if (BeginRef.isInvalid())
2363 return StmtError();
2364
Richard Smith02e85f32011-04-14 22:09:26 +00002365 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002366 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002367 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002368 if (!IncrExpr.isInvalid())
2369 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002370 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002371 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2372 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002373 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2374 return StmtError();
2375 }
2376
2377 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002378 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2379 VK_LValue, ColonLoc);
2380 if (BeginRef.isInvalid())
2381 return StmtError();
2382
Richard Smith02e85f32011-04-14 22:09:26 +00002383 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2384 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002385 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2386 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002387 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2388 return StmtError();
2389 }
2390
Richard Smitha05b3b52012-09-20 21:52:32 +00002391 // Attach *__begin as initializer for VD. Don't touch it if we're just
2392 // trying to determine whether this would be a valid range.
2393 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002394 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2395 /*TypeMayContainAuto=*/true);
2396 if (LoopVar->isInvalidDecl())
2397 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2398 }
2399 }
2400
Richard Smitha05b3b52012-09-20 21:52:32 +00002401 // Don't bother to actually allocate the result if we're just trying to
2402 // determine whether it would be valid.
2403 if (Kind == BFRK_Check)
2404 return StmtResult();
2405
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002406 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002407 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2408 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002409 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2410 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002411}
2412
Chad Rosier02a84392012-08-10 17:56:09 +00002413/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002414/// statement.
2415StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2416 if (!S || !B)
2417 return StmtError();
2418 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002419
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002420 ForStmt->setBody(B);
2421 return S;
2422}
2423
Richard Trieu3e1d4832015-04-13 22:08:55 +00002424// Warn when the loop variable is a const reference that creates a copy.
2425// Suggest using the non-reference type for copies. If a copy can be prevented
2426// suggest the const reference type that would do so.
2427// For instance, given "for (const &Foo : Range)", suggest
2428// "for (const Foo : Range)" to denote a copy is made for the loop. If
2429// possible, also suggest "for (const &Bar : Range)" if this type prevents
2430// the copy altogether.
2431static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2432 const VarDecl *VD,
2433 QualType RangeInitType) {
2434 const Expr *InitExpr = VD->getInit();
2435 if (!InitExpr)
2436 return;
2437
2438 QualType VariableType = VD->getType();
2439
Tim Shen4a05bb82016-06-21 20:29:17 +00002440 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2441 if (!Cleanups->cleanupsHaveSideEffects())
2442 InitExpr = Cleanups->getSubExpr();
2443
Richard Trieu3e1d4832015-04-13 22:08:55 +00002444 const MaterializeTemporaryExpr *MTE =
2445 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2446
2447 // No copy made.
2448 if (!MTE)
2449 return;
2450
2451 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2452
2453 // Searching for either UnaryOperator for dereference of a pointer or
2454 // CXXOperatorCallExpr for handling iterators.
2455 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2456 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2457 E = CCE->getArg(0);
2458 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2459 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2460 E = ME->getBase();
2461 } else {
2462 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2463 E = MTE->GetTemporaryExpr();
2464 }
2465 E = E->IgnoreImpCasts();
2466 }
2467
2468 bool ReturnsReference = false;
2469 if (isa<UnaryOperator>(E)) {
2470 ReturnsReference = true;
2471 } else {
2472 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2473 const FunctionDecl *FD = Call->getDirectCallee();
2474 QualType ReturnType = FD->getReturnType();
2475 ReturnsReference = ReturnType->isReferenceType();
2476 }
2477
2478 if (ReturnsReference) {
2479 // Loop variable creates a temporary. Suggest either to go with
2480 // non-reference loop variable to indiciate a copy is made, or
2481 // the correct time to bind a const reference.
2482 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2483 << VD << VariableType << E->getType();
2484 QualType NonReferenceType = VariableType.getNonReferenceType();
2485 NonReferenceType.removeLocalConst();
2486 QualType NewReferenceType =
2487 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2488 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2489 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2490 } else {
2491 // The range always returns a copy, so a temporary is always created.
2492 // Suggest removing the reference from the loop variable.
2493 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2494 << VD << RangeInitType;
2495 QualType NonReferenceType = VariableType.getNonReferenceType();
2496 NonReferenceType.removeLocalConst();
2497 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2498 << NonReferenceType << VD->getSourceRange();
2499 }
2500}
2501
2502// Warns when the loop variable can be changed to a reference type to
2503// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2504// "for (const Foo &x : Range)" if this form does not make a copy.
2505static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2506 const VarDecl *VD) {
2507 const Expr *InitExpr = VD->getInit();
2508 if (!InitExpr)
2509 return;
2510
2511 QualType VariableType = VD->getType();
2512
2513 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2514 if (!CE->getConstructor()->isCopyConstructor())
2515 return;
2516 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2517 if (CE->getCastKind() != CK_LValueToRValue)
2518 return;
2519 } else {
2520 return;
2521 }
2522
2523 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2524 // should be emitted. Also, only ignore POD types with trivial copy
2525 // constructors.
2526 if (VariableType.isPODType(SemaRef.Context))
2527 return;
2528
2529 // Suggest changing from a const variable to a const reference variable
2530 // if doing so will prevent a copy.
2531 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2532 << VD << VariableType << InitExpr->getType();
2533 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2534 << SemaRef.Context.getLValueReferenceType(VariableType)
2535 << VD->getSourceRange();
2536}
2537
2538/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2539/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2540/// using "const foo x" to show that a copy is made
2541/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2542/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2543/// prevent the copy.
2544/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2545/// Suggest "const foo &x" to prevent the copy.
2546static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2547 const CXXForRangeStmt *ForStmt) {
2548 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2549 ForStmt->getLocStart()) &&
2550 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2551 ForStmt->getLocStart()) &&
2552 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2553 ForStmt->getLocStart())) {
2554 return;
2555 }
2556
2557 const VarDecl *VD = ForStmt->getLoopVariable();
2558 if (!VD)
2559 return;
2560
2561 QualType VariableType = VD->getType();
2562
2563 if (VariableType->isIncompleteType())
2564 return;
2565
2566 const Expr *InitExpr = VD->getInit();
2567 if (!InitExpr)
2568 return;
2569
2570 if (VariableType->isReferenceType()) {
2571 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2572 ForStmt->getRangeInit()->getType());
2573 } else if (VariableType.isConstQualified()) {
2574 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2575 }
2576}
2577
Richard Smith02e85f32011-04-14 22:09:26 +00002578/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2579/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2580/// body cannot be performed until after the type of the range variable is
2581/// determined.
2582StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2583 if (!S || !B)
2584 return StmtError();
2585
Fariborz Jahanian00213472012-07-06 19:04:04 +00002586 if (isa<ObjCForCollectionStmt>(S))
2587 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002588
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002589 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2590 ForStmt->setBody(B);
2591
2592 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2593 diag::warn_empty_range_based_for_body);
2594
Richard Trieu3e1d4832015-04-13 22:08:55 +00002595 DiagnoseForRangeVariableCopies(*this, ForStmt);
2596
Richard Smith02e85f32011-04-14 22:09:26 +00002597 return S;
2598}
2599
Chris Lattnercab02a62011-02-17 20:34:02 +00002600StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2601 SourceLocation LabelLoc,
2602 LabelDecl *TheDecl) {
2603 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002604 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002605 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002606}
Chris Lattner1c310502007-05-31 06:00:00 +00002607
John McCalldadc5752010-08-24 06:29:42 +00002608StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002609Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002610 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002611 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002612 if (!E->isTypeDependent()) {
2613 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002614 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002615 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002616 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002617 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2618 if (ExprRes.isInvalid())
2619 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002620 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002621 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002622 return StmtError();
2623 }
John McCalla95172b2010-08-01 00:26:45 +00002624
Richard Smith945f8d32013-01-14 22:39:08 +00002625 ExprResult ExprRes = ActOnFinishFullExpr(E);
2626 if (ExprRes.isInvalid())
2627 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002628 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002629
John McCallaab3e412010-08-25 08:40:02 +00002630 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002631
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002632 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002633}
2634
Nico Weberd64657f2015-03-09 02:47:59 +00002635static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2636 const Scope &DestScope) {
2637 if (!S.CurrentSEHFinally.empty() &&
2638 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2639 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2640 }
2641}
2642
John McCalldadc5752010-08-24 06:29:42 +00002643StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002644Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002645 Scope *S = CurScope->getContinueParent();
2646 if (!S) {
2647 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002648 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002649 }
Nico Weberd64657f2015-03-09 02:47:59 +00002650 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002651
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002652 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002653}
2654
John McCalldadc5752010-08-24 06:29:42 +00002655StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002656Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002657 Scope *S = CurScope->getBreakParent();
2658 if (!S) {
2659 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002660 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002661 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002662 if (S->isOpenMPLoopScope())
2663 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2664 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002665 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002666
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002667 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002668}
2669
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002670/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002671/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002672///
Douglas Gregor5d369002011-01-21 18:05:27 +00002673/// \param ReturnType If we're determining the copy elision candidate for
2674/// a return statement, this is the return type of the function. If we're
2675/// determining the copy elision candidate for a throw expression, this will
2676/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002677///
Douglas Gregor5d369002011-01-21 18:05:27 +00002678/// \param E The expression being returned from the function or block, or
2679/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002680///
Douglas Gregor86394412011-05-20 15:00:53 +00002681/// \param AllowFunctionParameter Whether we allow function parameters to
2682/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2683/// we re-use this logic to determine whether we should try to move as part of
2684/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002685///
2686/// \returns The NRVO candidate variable, if the return statement may use the
2687/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002688VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2689 Expr *E,
2690 bool AllowFunctionParameter) {
2691 if (!getLangOpts().CPlusPlus)
2692 return nullptr;
2693
2694 // - in a return statement in a function [where] ...
2695 // ... the expression is the name of a non-volatile automatic object ...
2696 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002697 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002698 return nullptr;
2699 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2700 if (!VD)
2701 return nullptr;
2702
2703 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2704 return VD;
2705 return nullptr;
2706}
2707
2708bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2709 bool AllowFunctionParameter) {
2710 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002711 // - in a return statement in a function with ...
2712 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002713 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002714 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002715 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002716 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002717 if (!VDType->isDependentType() &&
2718 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2719 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002721
John McCall03318c12011-11-11 03:57:31 +00002722 // ...object (other than a function or catch-clause parameter)...
2723 if (VD->getKind() != Decl::Var &&
2724 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002725 return false;
2726 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002727
John McCall03318c12011-11-11 03:57:31 +00002728 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002729 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002730
2731 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002732 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002733
2734 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002735 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002736
2737 // Variables with higher required alignment than their type's ABI
2738 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002739 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002740 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002741 return false;
John McCall03318c12011-11-11 03:57:31 +00002742
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002743 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002744}
2745
Douglas Gregor626fbed2011-01-21 21:08:57 +00002746/// \brief Perform the initialization of a potentially-movable value, which
2747/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002748///
2749/// This routine implements C++0x [class.copy]p33, which attempts to treat
2750/// returned lvalues as rvalues in certain cases (to prefer move construction),
2751/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002753Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2754 const VarDecl *NRVOCandidate,
2755 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002756 Expr *Value,
2757 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002758 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759 // When the criteria for elision of a copy operation are met or would
2760 // be met save for the fact that the source object is a function
2761 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002762 // overload resolution to select the constructor for the copy is first
2763 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002764 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002765 if (AllowNRVO &&
2766 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002768 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002769
Douglas Gregorf282a762011-01-21 19:38:21 +00002770 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002772 = InitializationKind::CreateCopy(Value->getLocStart(),
2773 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002774 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775
2776 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002777 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002778 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002779 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002780 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002781 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2782 StepEnd = Seq.step_end();
2783 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002784 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002785 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002786
2787 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002788 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789
Douglas Gregorf282a762011-01-21 19:38:21 +00002790 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002791 = Constructor->getParamDecl(0)->getType()
2792 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793
Douglas Gregorf282a762011-01-21 19:38:21 +00002794 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002796 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2797 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002798 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002799
Douglas Gregorf282a762011-01-21 19:38:21 +00002800 // Promote "AsRvalue" to the heap, since we now need this
2801 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002802 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002803 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804
Douglas Gregorf282a762011-01-21 19:38:21 +00002805 // Complete type-checking the initialization of the return type
2806 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002807 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002808 }
2809 }
2810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811
Douglas Gregorf282a762011-01-21 19:38:21 +00002812 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002813 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002814 // (again) now with the return value expression as written.
2815 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002816 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002817
Douglas Gregorf282a762011-01-21 19:38:21 +00002818 return Res;
2819}
2820
Richard Smith4db51c22013-09-25 05:02:54 +00002821/// \brief Determine whether the declared return type of the specified function
2822/// contains 'auto'.
2823static bool hasDeducedReturnType(FunctionDecl *FD) {
2824 const FunctionProtoType *FPT =
2825 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002826 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002827}
2828
Eli Friedman34b49062012-01-26 03:00:14 +00002829/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2830/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002831///
John McCalldadc5752010-08-24 06:29:42 +00002832StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002833Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2834 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002835 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002836 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002837 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002838 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002839
Richard Smith4db51c22013-09-25 05:02:54 +00002840 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2841 // In C++1y, the return type may involve 'auto'.
2842 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2843 FunctionDecl *FD = CurLambda->CallOperator;
2844 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002845 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002846
2847 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2848 assert(AT && "lost auto type from lambda return type");
2849 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2850 FD->setInvalidDecl();
2851 return StmtError();
2852 }
Alp Toker314cc812014-01-25 16:55:45 +00002853 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002854 } else if (CurCap->HasImplicitReturnType) {
2855 // For blocks/lambdas with implicit return types, we check each return
2856 // statement individually, and deduce the common return type when the block
2857 // or lambda is completed.
2858 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002859 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002860 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2861 if (Result.isInvalid())
2862 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002863 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002864
Richard Smith5a0e50c2014-12-19 22:10:51 +00002865 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2866 // when deducing a return type for a lambda-expression (or by extension
2867 // for a block). These rules differ from the stated C++11 rules only in
2868 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002869 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002870 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002871 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002872 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002873 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002874 if (RetValExp) {
2875 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2876 // initializer list, because it is not an expression (even
2877 // though we represent it as one). We still deduce 'void'.
2878 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2879 << RetValExp->getSourceRange();
2880 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002881
Jordan Rosed39e5f12012-07-02 21:19:23 +00002882 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002883 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002884
2885 // Although we'll properly infer the type of the block once it's completed,
2886 // make sure we provide a return type now for better error recovery.
2887 if (CurCap->ReturnType.isNull())
2888 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002889 }
Eli Friedman34b49062012-01-26 03:00:14 +00002890 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002891
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002892 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002893 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2894 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2895 return StmtError();
2896 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002897 } else if (CapturedRegionScopeInfo *CurRegion =
2898 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2899 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2900 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002901 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002902 assert(CurLambda && "unknown kind of captured scope");
2903 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2904 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002905 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2906 return StmtError();
2907 }
2908 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002909
Steve Naroffc540d662008-09-03 18:15:37 +00002910 // Otherwise, verify that this result type matches the previous one. We are
2911 // pickier with blocks than for normal functions because we don't have GCC
2912 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002913 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002914 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002915 // Delay processing for now. TODO: there are lots of dependent
2916 // types we can conclusively prove aren't void.
2917 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002918 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002919 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002920 (RetValExp->isTypeDependent() ||
2921 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002922 if (!getLangOpts().CPlusPlus &&
2923 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002924 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002925 else {
2926 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002927 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002928 }
Steve Naroffc540d662008-09-03 18:15:37 +00002929 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002930 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002931 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2932 } else if (!RetValExp->isTypeDependent()) {
2933 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002934
John McCall5500ef22011-08-17 22:09:46 +00002935 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2936 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2937 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002938
John McCall5500ef22011-08-17 22:09:46 +00002939 // In C++ the return statement is handled via a copy initialization.
2940 // the C version of which boils down to CheckSingleAssignmentConstraints.
2941 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2942 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2943 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002944 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002945 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2946 FnRetType, RetValExp);
2947 if (Res.isInvalid()) {
2948 // FIXME: Cleanup temporaries here, anyway?
2949 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002950 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002951 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002952 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002953 } else {
2954 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002955 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002956
John McCall75f92b52011-08-17 21:34:14 +00002957 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002958 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2959 if (ER.isInvalid())
2960 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002961 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002962 }
John McCall5500ef22011-08-17 22:09:46 +00002963 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2964 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002965
Jordan Rosed39e5f12012-07-02 21:19:23 +00002966 // If we need to check for the named return value optimization,
2967 // or if we need to infer the return type,
2968 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002969 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002970 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002971
Richard Smith9f690bd2015-10-27 06:02:45 +00002972 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
2973 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
2974
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002975 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002976}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002977
Nico Weber72889432014-09-06 01:25:55 +00002978namespace {
2979/// \brief Marks all typedefs in all local classes in a type referenced.
2980///
2981/// In a function like
2982/// auto f() {
2983/// struct S { typedef int a; };
2984/// return S();
2985/// }
2986///
2987/// the local type escapes and could be referenced in some TUs but not in
2988/// others. Pretend that all local typedefs are always referenced, to not warn
2989/// on this. This isn't necessary if f has internal linkage, or the typedef
2990/// is private.
2991class LocalTypedefNameReferencer
2992 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2993public:
2994 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2995 bool VisitRecordType(const RecordType *RT);
2996private:
2997 Sema &S;
2998};
2999bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3000 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3001 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3002 R->isDependentType())
3003 return true;
3004 for (auto *TmpD : R->decls())
3005 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3006 if (T->getAccess() != AS_private || R->hasFriends())
3007 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3008 return true;
3009}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003010}
Nico Weber72889432014-09-06 01:25:55 +00003011
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003012TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003013 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003014 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3015 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003016 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003017}
3018
Richard Smith2a7d4812013-05-04 07:00:32 +00003019/// Deduce the return type for a function from a returned expression, per
3020/// C++1y [dcl.spec.auto]p6.
3021bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3022 SourceLocation ReturnLoc,
3023 Expr *&RetExpr,
3024 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003025 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003026 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003027
Richard Smithc58f38f2013-08-14 20:16:31 +00003028 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3029 // If the deduction is for a return statement and the initializer is
3030 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003031 Diag(RetExpr->getExprLoc(),
3032 getCurLambda() ? diag::err_lambda_return_init_list
3033 : diag::err_auto_fn_return_init_list)
3034 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003035 return true;
3036 }
3037
3038 if (FD->isDependentContext()) {
3039 // C++1y [dcl.spec.auto]p12:
3040 // Return type deduction [...] occurs when the definition is
3041 // instantiated even if the function body contains a return
3042 // statement with a non-type-dependent operand.
3043 assert(AT->isDeduced() && "should have deduced to dependent type");
3044 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003045 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003046
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003047 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003048 // Otherwise, [...] deduce a value for U using the rules of template
3049 // argument deduction.
3050 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3051
3052 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3053 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3054 << OrigResultType.getType() << RetExpr->getType();
3055
3056 if (DAR != DAR_Succeeded)
3057 return true;
Nico Weber72889432014-09-06 01:25:55 +00003058
3059 // If a local type is part of the returned type, mark its fields as
3060 // referenced.
3061 LocalTypedefNameReferencer Referencer(*this);
3062 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003063 } else {
3064 // In the case of a return with no operand, the initializer is considered
3065 // to be void().
3066 //
3067 // Deduction here can only succeed if the return type is exactly 'cv auto'
3068 // or 'decltype(auto)', so just check for that case directly.
3069 if (!OrigResultType.getType()->getAs<AutoType>()) {
3070 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3071 << OrigResultType.getType();
3072 return true;
3073 }
3074 // We always deduce U = void in this case.
3075 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3076 if (Deduced.isNull())
3077 return true;
3078 }
3079
3080 // If a function with a declared return type that contains a placeholder type
3081 // has multiple return statements, the return type is deduced for each return
3082 // statement. [...] if the type deduced is not the same in each deduction,
3083 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003084 QualType DeducedT = AT->getDeducedType();
3085 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003086 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003087 // It is possible that NewAT->getDeducedType() is null. When that happens,
3088 // we should not crash, instead we ignore this deduction.
3089 if (NewAT->getDeducedType().isNull())
3090 return false;
3091
Douglas Gregora602a152015-10-01 20:20:47 +00003092 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003093 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003094 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3095 NewAT->getDeducedType());
3096 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003097 const LambdaScopeInfo *LambdaSI = getCurLambda();
3098 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3099 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003100 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003101 << true /*IsLambda*/;
3102 } else {
3103 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3104 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003105 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003106 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003107 return true;
3108 }
3109 } else if (!FD->isInvalidDecl()) {
3110 // Update all declarations of the function to have the deduced return type.
3111 Context.adjustDeducedFunctionResultType(FD, Deduced);
3112 }
3113
3114 return false;
3115}
3116
John McCalldadc5752010-08-24 06:29:42 +00003117StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003118Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3119 Scope *CurScope) {
3120 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3121 if (R.isInvalid()) {
3122 return R;
3123 }
3124
3125 if (VarDecl *VD =
3126 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3127 CurScope->addNRVOCandidate(VD);
3128 } else {
3129 CurScope->setNoNRVO();
3130 }
3131
Nico Weberd64657f2015-03-09 02:47:59 +00003132 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3133
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003134 return R;
3135}
3136
3137StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003138 // Check for unexpanded parameter packs.
3139 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3140 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003141
Eli Friedman34b49062012-01-26 03:00:14 +00003142 if (isa<CapturingScopeInfo>(getCurFunction()))
3143 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003144
Chris Lattner79413952008-12-04 23:50:19 +00003145 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003146 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003147 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003148 bool isObjCMethod = false;
3149
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003150 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003151 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003152 if (FD->hasAttrs())
3153 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003154 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003155 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003156 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003157 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003158 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003159 isObjCMethod = true;
3160 if (MD->hasAttrs())
3161 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003162 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3163 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003164 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003165 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003166 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3167 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003168 }
3169 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003170 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003171
Richard Smith2a7d4812013-05-04 07:00:32 +00003172 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3173 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003174 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003175 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3176 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003177 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003178 FD->setInvalidDecl();
3179 return StmtError();
3180 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003181 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003182 }
3183 }
3184 }
3185
Richard Smithc58f38f2013-08-14 20:16:31 +00003186 bool HasDependentReturnType = FnRetType->isDependentType();
3187
Craig Topperc3ec1492014-05-26 06:22:03 +00003188 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003189 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003190 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003191 if (isa<InitListExpr>(RetValExp)) {
3192 // We simply never allow init lists as the return value of void
3193 // functions. This is compatible because this was never allowed before,
3194 // so there's no legacy code to deal with.
3195 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3196 int FunctionKind = 0;
3197 if (isa<ObjCMethodDecl>(CurDecl))
3198 FunctionKind = 1;
3199 else if (isa<CXXConstructorDecl>(CurDecl))
3200 FunctionKind = 2;
3201 else if (isa<CXXDestructorDecl>(CurDecl))
3202 FunctionKind = 3;
3203
3204 Diag(ReturnLoc, diag::err_return_init_list)
3205 << CurDecl->getDeclName() << FunctionKind
3206 << RetValExp->getSourceRange();
3207
3208 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003209 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003210 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003211 // C99 6.8.6.4p1 (ext_ since GCC warns)
3212 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003213 if (RetValExp->getType()->isVoidType()) {
3214 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3215 if (isa<CXXConstructorDecl>(CurDecl) ||
3216 isa<CXXDestructorDecl>(CurDecl))
3217 D = diag::err_ctor_dtor_returns_void;
3218 else
3219 D = diag::ext_return_has_void_expr;
3220 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003221 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003222 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003223 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003224 if (Result.isInvalid())
3225 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003226 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003227 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003228 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003229 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003230 // return of void in constructor/destructor is illegal in C++.
3231 if (D == diag::err_ctor_dtor_returns_void) {
3232 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3233 Diag(ReturnLoc, D)
3234 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3235 << RetValExp->getSourceRange();
3236 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003237 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003238 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003239 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003240 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003241
3242 int FunctionKind = 0;
3243 if (isa<ObjCMethodDecl>(CurDecl))
3244 FunctionKind = 1;
3245 else if (isa<CXXConstructorDecl>(CurDecl))
3246 FunctionKind = 2;
3247 else if (isa<CXXDestructorDecl>(CurDecl))
3248 FunctionKind = 3;
3249
Nick Lewycky1be750a2011-06-01 07:44:31 +00003250 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003251 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003252 << RetValExp->getSourceRange();
3253 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003254 }
Mike Stump11289f42009-09-09 15:08:12 +00003255
Sebastian Redleef474c2012-02-22 10:50:08 +00003256 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003257 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3258 if (ER.isInvalid())
3259 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003260 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003261 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263
Craig Topperc3ec1492014-05-26 06:22:03 +00003264 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003265 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003266 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003267
David Majnemer2887ad32014-12-13 08:12:56 +00003268 unsigned DiagID;
3269 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3270 // C++11 [stmt.return]p2
3271 DiagID = diag::err_constexpr_return_missing_expr;
3272 FD->setInvalidDecl();
3273 } else if (getLangOpts().C99) {
3274 // C99 6.8.6.4p1 (ext_ since GCC warns)
3275 DiagID = diag::ext_return_missing_expr;
3276 } else {
3277 // C90 6.6.6.4p4
3278 DiagID = diag::warn_return_missing_expr;
3279 }
3280
3281 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003282 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003283 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003284 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003285
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003286 Result = new (Context) ReturnStmt(ReturnLoc);
3287 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003288 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003289 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003290
3291 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3292
3293 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3294 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3295 // function return.
3296
3297 // In C++ the return statement is handled via a copy initialization,
3298 // the C version of which boils down to CheckSingleAssignmentConstraints.
3299 if (RetValExp)
3300 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003301 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003302 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003304 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003306 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003307 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003308 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003309 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003310 return StmtError();
3311 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003312 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003313
3314 // If we have a related result type, we need to implicitly
3315 // convert back to the formal result type. We can't pretend to
3316 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003317 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003318 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003319 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3320 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003321 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3322 if (Res.isInvalid()) {
3323 // FIXME: Clean up temporaries here anyway?
3324 return StmtError();
3325 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003326 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003327 }
3328
Artyom Skrobov9f213442014-01-24 11:10:39 +00003329 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3330 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
John McCallacf0ee52010-10-08 02:01:28 +00003333 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003334 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3335 if (ER.isInvalid())
3336 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003337 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003338 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003339 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
3342 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003343 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003344 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003345 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003346
Richard Smith9f690bd2015-10-27 06:02:45 +00003347 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3348 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3349
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003350 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003351}
3352
John McCalldadc5752010-08-24 06:29:42 +00003353StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003354Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003355 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003356 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003357 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003358 if (Var && Var->isInvalidDecl())
3359 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003361 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003362}
3363
John McCalldadc5752010-08-24 06:29:42 +00003364StmtResult
John McCallb268a282010-08-23 23:25:46 +00003365Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003366 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003367}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003368
John McCalldadc5752010-08-24 06:29:42 +00003369StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003371 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003372 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003373 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3374
John McCallaab3e412010-08-25 08:40:02 +00003375 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003376 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003377 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3378 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003379}
3380
John McCall0bd3e402012-05-08 21:41:25 +00003381StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003382 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003383 ExprResult Result = DefaultLvalueConversion(Throw);
3384 if (Result.isInvalid())
3385 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003386
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003387 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003388 if (Result.isInvalid())
3389 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003390 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003391
Douglas Gregor2900c162010-04-22 21:44:01 +00003392 QualType ThrowType = Throw->getType();
3393 // Make sure the expression type is an ObjC pointer or "void *".
3394 if (!ThrowType->isDependentType() &&
3395 !ThrowType->isObjCObjectPointerType()) {
3396 const PointerType *PT = ThrowType->getAs<PointerType>();
3397 if (!PT || !PT->getPointeeType()->isVoidType())
3398 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3399 << Throw->getType() << Throw->getSourceRange());
3400 }
3401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003403 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003404}
3405
John McCalldadc5752010-08-24 06:29:42 +00003406StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003408 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003409 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003410 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3411
John McCallb268a282010-08-23 23:25:46 +00003412 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003413 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003414 // in the context of an @catch clause).
3415 Scope *AtCatchParent = CurScope;
3416 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3417 AtCatchParent = AtCatchParent->getParent();
3418 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003419 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 }
John McCallb268a282010-08-23 23:25:46 +00003421 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003422}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003423
John McCalld9bb7432011-07-27 21:50:02 +00003424ExprResult
3425Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3426 ExprResult result = DefaultLvalueConversion(operand);
3427 if (result.isInvalid())
3428 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003429 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003430
3431 // Make sure the expression type is an ObjC pointer or "void *".
3432 QualType type = operand->getType();
3433 if (!type->isDependentType() &&
3434 !type->isObjCObjectPointerType()) {
3435 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003436 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3437 if (getLangOpts().CPlusPlus) {
3438 if (RequireCompleteType(atLoc, type,
3439 diag::err_incomplete_receiver_type))
3440 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3441 << type << operand->getSourceRange();
3442
3443 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3444 if (!result.isUsable())
3445 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3446 << type << operand->getSourceRange();
3447
3448 operand = result.get();
3449 } else {
3450 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3451 << type << operand->getSourceRange();
3452 }
3453 }
John McCalld9bb7432011-07-27 21:50:02 +00003454 }
3455
3456 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003457 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003458}
3459
John McCalldadc5752010-08-24 06:29:42 +00003460StmtResult
John McCallb268a282010-08-23 23:25:46 +00003461Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3462 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003463 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003464 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003465 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003466}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003467
3468/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3469/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003470StmtResult
John McCall48871652010-08-21 09:40:31 +00003471Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003472 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003473 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003474 return new (Context)
3475 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003476}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003477
John McCall31168b02011-06-15 23:02:42 +00003478StmtResult
3479Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3480 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003481 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003482}
3483
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003484namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003485class CatchHandlerType {
3486 QualType QT;
3487 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003488
Aaron Ballman8aee642902015-04-08 00:05:29 +00003489 // This is a special constructor to be used only with DenseMapInfo's
3490 // getEmptyKey() and getTombstoneKey() functions.
3491 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3492 enum Unique { ForDenseMap };
3493 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3494
Sebastian Redl63c4da02009-07-29 17:15:45 +00003495public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003496 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003497 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003498 /// level pointer and cv-qualifiers.
3499 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3500 if (QT->isPointerType())
3501 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003502
Aaron Ballman8aee642902015-04-08 00:05:29 +00003503 if (IsPointer || QT->isReferenceType())
3504 QT = QT->getPointeeType();
3505 QT = QT.getUnqualifiedType();
3506 }
3507
3508 /// Used when creating a CatchHandlerType from a base class type; pretends the
3509 /// type passed in had the pointer qualifier, does not need to get an
3510 /// unqualified type.
3511 CatchHandlerType(QualType QT, bool IsPointer)
3512 : QT(QT), IsPointer(IsPointer) {}
3513
3514 QualType underlying() const { return QT; }
3515 bool isPointer() const { return IsPointer; }
3516
3517 friend bool operator==(const CatchHandlerType &LHS,
3518 const CatchHandlerType &RHS) {
3519 // If the pointer qualification does not match, we can return early.
3520 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003521 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003522 // Otherwise, check the underlying type without cv-qualifiers.
3523 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003524 }
3525};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003526} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003527
Aaron Ballman8aee642902015-04-08 00:05:29 +00003528namespace llvm {
3529template <> struct DenseMapInfo<CatchHandlerType> {
3530 static CatchHandlerType getEmptyKey() {
3531 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3532 CatchHandlerType::ForDenseMap);
3533 }
3534
3535 static CatchHandlerType getTombstoneKey() {
3536 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3537 CatchHandlerType::ForDenseMap);
3538 }
3539
3540 static unsigned getHashValue(const CatchHandlerType &Base) {
3541 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3542 }
3543
3544 static bool isEqual(const CatchHandlerType &LHS,
3545 const CatchHandlerType &RHS) {
3546 return LHS == RHS;
3547 }
3548};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003549}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003550
3551namespace {
3552class CatchTypePublicBases {
3553 ASTContext &Ctx;
3554 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3555 const bool CheckAgainstPointer;
3556
3557 CXXCatchStmt *FoundHandler;
3558 CanQualType FoundHandlerType;
3559
3560public:
3561 CatchTypePublicBases(
3562 ASTContext &Ctx,
3563 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3564 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3565 FoundHandler(nullptr) {}
3566
3567 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3568 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3569
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003570 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003571 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003572 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003573 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003574 auto I = M.find(Check);
3575 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003576 FoundHandler = I->second;
3577 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003578 return true;
3579 }
3580 }
3581 return false;
3582 }
3583};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003584}
Dan Gohman28ade552010-07-26 21:25:24 +00003585
Sebastian Redl9b244a82008-12-22 21:35:02 +00003586/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3587/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003588StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3589 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003590 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003591 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003592 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003593 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003594
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003595 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3596 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3597
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003598 sema::FunctionScopeInfo *FSI = getCurFunction();
3599
Reid Klecknere7175912015-02-02 22:15:31 +00003600 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003601 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003602 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003603 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003604 }
3605
Robert Wilhelmcafda822013-08-22 09:20:03 +00003606 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003607 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003608 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003609
Aaron Ballman8aee642902015-04-08 00:05:29 +00003610 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003611 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003612 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003613
Aaron Ballman8aee642902015-04-08 00:05:29 +00003614 // Diagnose when the handler is a catch-all handler, but it isn't the last
3615 // handler for the try block. [except.handle]p5. Also, skip exception
3616 // declarations that are invalid, since we can't usefully report on them.
3617 if (!H->getExceptionDecl()) {
3618 if (i < NumHandlers - 1)
3619 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003620 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003621 } else if (H->getExceptionDecl()->isInvalidDecl())
3622 continue;
3623
3624 // Walk the type hierarchy to diagnose when this type has already been
3625 // handled (duplication), or cannot be handled (derivation inversion). We
3626 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003627 CatchHandlerType HandlerCHT =
3628 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003629
3630 // We can ignore whether the type is a reference or a pointer; we need the
3631 // underlying declaration type in order to get at the underlying record
3632 // decl, if there is one.
3633 QualType Underlying = HandlerCHT.underlying();
3634 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3635 if (!RD->hasDefinition())
3636 continue;
3637 // Check that none of the public, unambiguous base classes are in the
3638 // map ([except.handle]p1). Give the base classes the same pointer
3639 // qualification as the original type we are basing off of. This allows
3640 // comparison against the handler type using the same top-level pointer
3641 // as the original type.
3642 CXXBasePaths Paths;
3643 Paths.setOrigin(RD);
3644 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003645 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003646 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3647 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3648 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3649 diag::warn_exception_caught_by_earlier_handler)
3650 << H->getCaughtType();
3651 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3652 diag::note_previous_exception_handler)
3653 << Problem->getCaughtType();
3654 }
3655 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003656 }
Mike Stump11289f42009-09-09 15:08:12 +00003657
Aaron Ballman8aee642902015-04-08 00:05:29 +00003658 // Add the type the list of ones we have handled; diagnose if we've already
3659 // handled it.
3660 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3661 if (!R.second) {
3662 const CXXCatchStmt *Problem = R.first->second;
3663 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3664 diag::warn_exception_caught_by_earlier_handler)
3665 << H->getCaughtType();
3666 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3667 diag::note_previous_exception_handler)
3668 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003669 }
3670 }
Mike Stump11289f42009-09-09 15:08:12 +00003671
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003672 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003673
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003674 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003675}
John Wiegley1c0675e2011-04-28 01:08:34 +00003676
Reid Klecknere7175912015-02-02 22:15:31 +00003677StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3678 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003679 assert(TryBlock && Handler);
3680
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003681 sema::FunctionScopeInfo *FSI = getCurFunction();
3682
Reid Klecknere7175912015-02-02 22:15:31 +00003683 // SEH __try is incompatible with C++ try. Borland appears to support this,
3684 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003685 if (!getLangOpts().Borland) {
3686 if (FSI->FirstCXXTryLoc.isValid()) {
3687 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3688 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3689 }
Reid Klecknere7175912015-02-02 22:15:31 +00003690 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003691
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003692 FSI->setHasSEHTry(TryLoc);
3693
3694 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3695 // track if they use SEH.
3696 DeclContext *DC = CurContext;
3697 while (DC && !DC->isFunctionOrMethod())
3698 DC = DC->getParent();
3699 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3700 if (FD)
3701 FD->setUsesSEHTry(true);
3702 else
3703 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003704
Reid Kleckner8819a402015-07-10 00:16:25 +00003705 // Reject __try on unsupported targets.
3706 if (!Context.getTargetInfo().isSEHTrySupported())
3707 Diag(TryLoc, diag::err_seh_try_unsupported);
3708
Reid Klecknere7175912015-02-02 22:15:31 +00003709 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003710}
3711
3712StmtResult
3713Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3714 Expr *FilterExpr,
3715 Stmt *Block) {
3716 assert(FilterExpr && Block);
3717
3718 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003719 return StmtError(Diag(FilterExpr->getExprLoc(),
3720 diag::err_filter_expression_integral)
3721 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003722 }
3723
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003724 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003725}
3726
Nico Weberd64657f2015-03-09 02:47:59 +00003727void Sema::ActOnStartSEHFinallyBlock() {
3728 CurrentSEHFinally.push_back(CurScope);
3729}
3730
Nico Weberce903292015-03-09 03:17:15 +00003731void Sema::ActOnAbortSEHFinallyBlock() {
3732 CurrentSEHFinally.pop_back();
3733}
3734
Nico Weberd64657f2015-03-09 02:47:59 +00003735StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003736 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003737 CurrentSEHFinally.pop_back();
3738 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003739}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003740
Nico Weberc7d05962014-07-06 22:32:59 +00003741StmtResult
3742Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003743 Scope *SEHTryParent = CurScope;
3744 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3745 SEHTryParent = SEHTryParent->getParent();
3746 if (!SEHTryParent)
3747 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003748 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003749
Nico Weber9b982072014-07-07 00:12:30 +00003750 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003751}
3752
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003753StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3754 bool IsIfExists,
3755 NestedNameSpecifierLoc QualifierLoc,
3756 DeclarationNameInfo NameInfo,
3757 Stmt *Nested)
3758{
3759 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003760 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003761 cast<CompoundStmt>(Nested));
3762}
3763
3764
Chad Rosier02a84392012-08-10 17:56:09 +00003765StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003766 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003767 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003768 UnqualifiedId &Name,
3769 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003770 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003771 SS.getWithLocInContext(Context),
3772 GetNameFromUnqualifiedId(Name),
3773 Nested);
3774}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003775
3776RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003777Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3778 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003779 DeclContext *DC = CurContext;
3780 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3781 DC = DC->getParent();
3782
Craig Topperc3ec1492014-05-26 06:22:03 +00003783 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003784 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003785 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3786 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003787 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003788 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003789
Alexey Bataev330de032014-10-29 12:21:55 +00003790 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003791 DC->addDecl(RD);
3792 RD->setImplicit();
3793 RD->startDefinition();
3794
Alexey Bataev9959db52014-05-06 10:08:46 +00003795 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003796 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003797 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003798 return RD;
3799}
3800
3801static void buildCapturedStmtCaptureList(
3802 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3803 SmallVectorImpl<Expr *> &CaptureInits,
3804 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3805
3806 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3807 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3808
3809 if (Cap->isThisCapture()) {
3810 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3811 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003812 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003813 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003814 } else if (Cap->isVLATypeCapture()) {
3815 Captures.push_back(
3816 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3817 CaptureInits.push_back(nullptr);
3818 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003819 }
3820
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003821 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003822 Cap->isReferenceCapture()
3823 ? CapturedStmt::VCK_ByRef
3824 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003825 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003826 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003827 }
3828}
3829
3830void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003831 CapturedRegionKind Kind,
3832 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003833 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003834 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003835
Alexey Bataev9959db52014-05-06 10:08:46 +00003836 // Build the context parameter
3837 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3838 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3839 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3840 ImplicitParamDecl *Param
3841 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3842 DC->addDecl(Param);
3843
3844 CD->setContextParam(0, Param);
3845
3846 // Enter the capturing scope for this captured region.
3847 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3848
3849 if (CurScope)
3850 PushDeclContext(CurScope, CD);
3851 else
3852 CurContext = CD;
3853
3854 PushExpressionEvaluationContext(PotentiallyEvaluated);
3855}
3856
3857void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3858 CapturedRegionKind Kind,
3859 ArrayRef<CapturedParamNameType> Params) {
3860 CapturedDecl *CD = nullptr;
3861 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3862
3863 // Build the context parameter
3864 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3865 bool ContextIsFound = false;
3866 unsigned ParamNum = 0;
3867 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3868 E = Params.end();
3869 I != E; ++I, ++ParamNum) {
3870 if (I->second.isNull()) {
3871 assert(!ContextIsFound &&
3872 "null type has been found already for '__context' parameter");
3873 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3874 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3875 ImplicitParamDecl *Param
3876 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3877 DC->addDecl(Param);
3878 CD->setContextParam(ParamNum, Param);
3879 ContextIsFound = true;
3880 } else {
3881 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3882 ImplicitParamDecl *Param
3883 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3884 DC->addDecl(Param);
3885 CD->setParam(ParamNum, Param);
3886 }
3887 }
3888 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003889 if (!ContextIsFound) {
3890 // Add __context implicitly if it is not specified.
3891 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3892 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3893 ImplicitParamDecl *Param =
3894 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3895 DC->addDecl(Param);
3896 CD->setContextParam(ParamNum, Param);
3897 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003898 // Enter the capturing scope for this captured region.
3899 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3900
3901 if (CurScope)
3902 PushDeclContext(CurScope, CD);
3903 else
3904 CurContext = CD;
3905
3906 PushExpressionEvaluationContext(PotentiallyEvaluated);
3907}
3908
Wei Pan17fbf6e2013-05-04 03:59:06 +00003909void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003910 DiscardCleanupsInEvaluationContext();
3911 PopExpressionEvaluationContext();
3912
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003913 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3914 RecordDecl *Record = RSI->TheRecordDecl;
3915 Record->setInvalidDecl();
3916
Aaron Ballman62e47c42014-03-10 13:43:55 +00003917 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003918 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3919 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003920
Wei Pan17fbf6e2013-05-04 03:59:06 +00003921 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003922 PopFunctionScopeInfo();
3923}
3924
3925StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3926 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3927
3928 SmallVector<CapturedStmt::Capture, 4> Captures;
3929 SmallVector<Expr *, 4> CaptureInits;
3930 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3931
3932 CapturedDecl *CD = RSI->TheCapturedDecl;
3933 RecordDecl *RD = RSI->TheRecordDecl;
3934
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003935 CapturedStmt *Res = CapturedStmt::Create(
3936 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
3937 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003938
3939 CD->setBody(Res->getCapturedStmt());
3940 RD->completeDefinition();
3941
Wei Pan17fbf6e2013-05-04 03:59:06 +00003942 DiscardCleanupsInEvaluationContext();
3943 PopExpressionEvaluationContext();
3944
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003945 PopDeclContext();
3946 PopFunctionScopeInfo();
3947
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003948 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003949}