blob: 3f63854ec0bdd029a0388c560331eb6a01d28007 [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"
Chris Lattneraf8d5812006-11-10 05:07:45 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000042
Richard Smith945f8d32013-01-14 22:39:08 +000043StmtResult Sema::ActOnExprStmt(ExprResult FE) {
44 if (FE.isInvalid())
45 return StmtError();
46
47 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
48 /*DiscardedValue*/ true);
49 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000050 return StmtError();
51
Chris Lattner903eb512008-07-25 23:18:17 +000052 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
53 // void expression for its side effects. Conversion to void allows any
54 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000055
Chris Lattner903eb512008-07-25 23:18:17 +000056 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000057 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000058}
59
60
John McCalleaef89b2013-03-22 02:10:40 +000061StmtResult Sema::ActOnExprStmtError() {
62 DiscardCleanupsInEvaluationContext();
63 return StmtError();
64}
65
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000066StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000067 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000068 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000069}
70
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000071StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
72 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000073 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnercbafe8d2009-04-12 20:13:14 +000075 // If we have an invalid decl, just return an error.
76 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000077
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000078 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000079}
Chris Lattneraf8d5812006-11-10 05:07:45 +000080
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000081void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000082 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 // If we don't have a declaration, or we have an invalid declaration,
85 // just return.
86 if (DG.isNull() || !DG.isSingleDecl())
87 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000088
Douglas Gregor2eb1c572013-04-08 20:52:24 +000089 Decl *decl = DG.getSingleDecl();
90 if (!decl || decl->isInvalidDecl())
91 return;
92
93 // Only variable declarations are permitted.
94 VarDecl *var = dyn_cast<VarDecl>(decl);
95 if (!var) {
96 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
97 decl->setInvalidDecl();
98 return;
99 }
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // foreach variables are never actually initialized in the way that
102 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000103 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000104
John McCalld4631322011-06-17 06:42:21 +0000105 // In ARC, we don't need to retain the iteration variable of a fast
106 // enumeration loop. Rather than actually trying to catch that
107 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000108 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000109 QualType type = var->getType();
110
111 // Only do this if we inferred the lifetime. Inferred lifetime
112 // will show up as a local qualifier because explicit lifetime
113 // should have shown up as an AttributedType instead.
114 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
115 // Add 'const' and mark the variable as pseudo-strong.
116 var->setType(type.withConst());
117 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000118 }
119 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000120}
121
Richard Trieu99e1c952014-03-11 03:11:08 +0000122/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
123/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124///
125/// Adding a cast to void (or other expression wrappers) will prevent the
126/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000127static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000128 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000129 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
131 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000132 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000133 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000134
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000136 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000137 IsNotEqual = Op->getOpcode() == BO_NE;
138 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000139 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000140 switch (Op->getOperator()) {
141 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000142 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000143 case OO_EqualEqual:
144 case OO_ExclaimEqual:
145 IsRelational = false;
146 break;
147 case OO_Less:
148 case OO_Greater:
149 case OO_GreaterEqual:
150 case OO_LessEqual:
151 IsRelational = true;
152 break;
153 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000156 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
157 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000158 } else {
159 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000160 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000161 }
162
163 // Suppress warnings when the operator, suspicious as it may be, comes from
164 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000165 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000166 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000167
Chandler Carruthe2669392011-08-17 09:34:37 +0000168 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000171 // If the LHS is a plausible entity to assign to, provide a fixit hint to
172 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000173 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000174 if (IsNotEqual)
175 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
176 << FixItHint::CreateReplacement(Loc, "|=");
177 else
178 S.Diag(Loc, diag::note_equality_comparison_to_assign)
179 << FixItHint::CreateReplacement(Loc, "=");
180 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000181
182 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000183}
184
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000185void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000186 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
187 return DiagnoseUnusedExprResult(Label->getSubStmt());
188
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000189 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000190 if (!E)
191 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000192
193 // If we are in an unevaluated expression context, then there can be no unused
194 // results because the results aren't expected to be used in the first place.
195 if (isUnevaluatedContext())
196 return;
197
Nico Weber0e631632015-10-27 19:47:40 +0000198 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000199 // In most cases, we don't want to warn if the expression is written in a
200 // macro body, or if the macro comes from a system header. If the offending
201 // expression is a call to a function with the warn_unused_result attribute,
202 // we warn no matter the location. Because of the order in which the various
203 // checks need to happen, we factor out the macro-related test here.
204 bool ShouldSuppress =
205 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
206 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000207
Eli Friedmanc11535c2012-05-24 00:47:05 +0000208 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000209 SourceLocation Loc;
210 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000211 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner6dc7e572012-08-31 22:39:21 +0000214 // If this is a GNU statement expression expanded from a macro, it is probably
215 // unused because it is a function-like macro that can be used as either an
216 // expression or statement. Don't warn, because it is almost certainly a
217 // false positive.
218 if (isa<StmtExpr>(E) && Loc.isMacroID())
219 return;
220
Nico Weber0e631632015-10-27 19:47:40 +0000221 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
222 // That macro is frequently used to suppress "unused parameter" warnings,
223 // but its implementation makes clang's -Wunused-value fire. Prevent this.
224 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
225 SourceLocation SpellLoc = Loc;
226 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
227 return;
228 }
229
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000230 // Okay, we have an unused result. Depending on what the base expression is,
231 // we might want to make a more specific diagnostic. Check for one of these
232 // cases now.
233 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000234 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000235 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000236 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
237 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000238
Chandler Carruthe2669392011-08-17 09:34:37 +0000239 if (DiagnoseUnusedComparison(*this, E))
240 return;
241
Eli Friedmanc11535c2012-05-24 00:47:05 +0000242 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000243 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000244 if (E->getType()->isVoidType())
245 return;
246
Chris Lattner1a6babf2009-10-13 04:53:48 +0000247 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000248 // a more specific message to make it clear what is happening. If the call
249 // is written in a macro body, only warn if it has the warn_unused_result
250 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000251 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000252 if (const Attr *A = isa<FunctionDecl>(FD)
253 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
254 : FD->getAttr<WarnUnusedResultAttr>()) {
255 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000256 return;
257 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000258 if (ShouldSuppress)
259 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000260 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000261 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
262 return;
263 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000264 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000265 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
266 return;
267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000269 } else if (ShouldSuppress)
270 return;
271
272 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000273 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000274 Diag(Loc, diag::err_arc_unused_init_message) << R1;
275 return;
276 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000277 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000278 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000279 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
280 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000281 return;
282 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000283 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000284 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
285 const Expr *Source = POE->getSyntacticForm();
286 if (isa<ObjCSubscriptRefExpr>(Source))
287 DiagID = diag::warn_unused_container_subscript_expr;
288 else
289 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000290 } else if (const CXXFunctionalCastExpr *FC
291 = dyn_cast<CXXFunctionalCastExpr>(E)) {
292 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
293 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
294 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000295 }
John McCall2351cb92010-04-06 22:24:14 +0000296 // Diagnose "(void*) blah" as a typo for "(void) blah".
297 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
298 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
299 QualType T = TI->getType();
300
301 // We really do want to use the non-canonical type here.
302 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000303 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000304
305 Diag(Loc, diag::warn_unused_voidptr)
306 << FixItHint::CreateRemoval(TL.getStarLoc());
307 return;
308 }
309 }
310
Eli Friedmanc11535c2012-05-24 00:47:05 +0000311 if (E->isGLValue() && E->getType().isVolatileQualified()) {
312 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
313 return;
314 }
315
Craig Topperc3ec1492014-05-26 06:22:03 +0000316 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000317}
318
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000319void Sema::ActOnStartOfCompoundStmt() {
320 PushCompoundScope();
321}
322
323void Sema::ActOnFinishOfCompoundStmt() {
324 PopCompoundScope();
325}
326
327sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
328 return getCurFunction()->CompoundScopes.back();
329}
330
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000331StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
332 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
333 const unsigned NumElts = Elts.size();
334
Chris Lattnerd864daf2007-08-27 04:29:41 +0000335 // If we're in C89 mode, check that we don't have any decls after stmts. If
336 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000337 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000338 // Note that __extension__ can be around a decl.
339 unsigned i = 0;
340 // Skip over all declarations.
341 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
342 /*empty*/;
343
344 // We found the end of the list or a statement. Scan for another declstmt.
345 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
346 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattnerd864daf2007-08-27 04:29:41 +0000348 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000349 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000350 Diag(D->getLocation(), diag::ext_mixed_decls_code);
351 }
352 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000353 // Warn about unused expressions in statements.
354 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000355 // Ignore statements that are last in a statement expression.
356 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000357 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000358
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000359 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000360 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000361
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000362 // Check for suspicious empty body (null statement) in `for' and `while'
363 // statements. Don't do anything for template instantiations, this just adds
364 // noise.
365 if (NumElts != 0 && !CurrentInstantiationScope &&
366 getCurCompoundScope().HasEmptyLoopBodies) {
367 for (unsigned i = 0; i != NumElts - 1; ++i)
368 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
369 }
370
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000371 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000372}
373
John McCalldadc5752010-08-24 06:29:42 +0000374StmtResult
John McCallb268a282010-08-23 23:25:46 +0000375Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
376 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000377 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000378 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000379
John McCallaab3e412010-08-25 08:40:02 +0000380 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000381 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000382 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000383 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000384
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000385 ExprResult LHS =
386 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
387 if (!getLangOpts().CPlusPlus11)
388 return VerifyIntegerConstantExpression(E);
389 if (Expr *CondExpr =
390 getCurFunction()->SwitchStack.back()->getCond()) {
391 QualType CondType = CondExpr->getType();
392 llvm::APSInt TempVal;
393 return CheckConvertedConstantExpression(E, CondType, TempVal,
394 CCEK_CaseValue);
395 }
396 return ExprError();
397 });
398 if (LHS.isInvalid())
399 return StmtError();
400 LHSVal = LHS.get();
401
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000402 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000403 // C99 6.8.4.2p3: The expression shall be an integer constant.
404 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000405 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000407 if (!LHSVal)
408 return StmtError();
409 }
Richard Smithf8379a02012-01-18 23:55:52 +0000410
411 // GCC extension: The expression shall be an integer constant.
412
Richard Smithf4c51d92012-02-04 09:53:13 +0000413 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000414 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000415 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000416 }
417 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000418
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000419 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000420 getLangOpts().CPlusPlus11);
421 if (LHS.isInvalid())
422 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000423
Richard Smith5b555da2014-11-20 01:24:12 +0000424 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
425 getLangOpts().CPlusPlus11)
426 : ExprResult();
427 if (RHS.isInvalid())
428 return StmtError();
429
430 CaseStmt *CS = new (Context)
431 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000432 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000433 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000434}
435
Chris Lattner34a22092009-03-04 04:23:07 +0000436/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000437void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000438 DiagnoseUnusedExprResult(SubStmt);
439
Chris Lattner34a22092009-03-04 04:23:07 +0000440 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000441 CS->setSubStmt(SubStmt);
442}
443
John McCalldadc5752010-08-24 06:29:42 +0000444StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000445Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000446 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000447 DiagnoseUnusedExprResult(SubStmt);
448
John McCallaab3e412010-08-25 08:40:02 +0000449 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000450 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000452 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000453
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000454 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000455 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000456 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000457}
458
John McCalldadc5752010-08-24 06:29:42 +0000459StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000460Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
461 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000462 // If the label was multiply defined, reject it now.
463 if (TheDecl->getStmt()) {
464 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
465 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000466 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000467 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000468
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000469 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000470 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
471 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000472 if (!TheDecl->isGnuLocal()) {
473 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000474 if (!TheDecl->isMSAsmLabel()) {
475 // Don't update the location of MS ASM labels. These will result in
476 // a diagnostic, and changing the location here will mess that up.
477 TheDecl->setLocation(IdentLoc);
478 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000479 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000480 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000481}
482
Richard Smithc202b282012-04-14 00:33:13 +0000483StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000484 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000485 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000486 // Fill in the declaration and return it.
487 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000488 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000489}
490
Richard Trieufaca2d82016-02-18 23:58:40 +0000491namespace {
492class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
493 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
494 Sema &SemaRef;
495public:
496 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
497 void VisitBinaryOperator(BinaryOperator *E) {
498 if (E->getOpcode() == BO_Comma)
499 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
500 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
501 }
502};
503}
504
John McCalldadc5752010-08-24 06:29:42 +0000505StmtResult
John McCall48871652010-08-21 09:40:31 +0000506Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000507 Stmt *thenStmt, SourceLocation ElseLoc,
508 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000509 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000510
Craig Topperc3ec1492014-05-26 06:22:03 +0000511 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000512 if (CondVar) {
513 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000514 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +0000515 CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
Douglas Gregor633caca2009-11-23 23:44:04 +0000516 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000517 Expr *ConditionExpr = CondResult.getAs<Expr>();
Olivier Goffart122993b2015-10-11 17:27:29 +0000518 if (ConditionExpr) {
Richard Trieufaca2d82016-02-18 23:58:40 +0000519
520 if (!Diags.isIgnored(diag::warn_comma_operator,
521 ConditionExpr->getExprLoc()))
522 CommaVisitor(*this).Visit(ConditionExpr);
523
Olivier Goffart122993b2015-10-11 17:27:29 +0000524 DiagnoseUnusedExprResult(thenStmt);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525
Olivier Goffart122993b2015-10-11 17:27:29 +0000526 if (!elseStmt) {
527 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
528 diag::warn_empty_if_body);
529 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000530
Olivier Goffart122993b2015-10-11 17:27:29 +0000531 DiagnoseUnusedExprResult(elseStmt);
532 } else {
533 // Create a dummy Expr for the condition for error recovery
534 ConditionExpr = new (Context) OpaqueValueExpr(SourceLocation(),
535 Context.BoolTy, VK_RValue);
Anders Carlssondb83d772007-10-10 20:50:11 +0000536 }
537
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000538 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
539 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000540}
Steve Naroff86272ea2007-05-29 02:14:17 +0000541
Chris Lattner67998452007-08-23 18:29:20 +0000542namespace {
543 struct CaseCompareFunctor {
544 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
545 const llvm::APSInt &RHS) {
546 return LHS.first < RHS;
547 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000548 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
549 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
550 return LHS.first < RHS.first;
551 }
Chris Lattner67998452007-08-23 18:29:20 +0000552 bool operator()(const llvm::APSInt &LHS,
553 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
554 return LHS < RHS.first;
555 }
556 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000557}
Chris Lattner67998452007-08-23 18:29:20 +0000558
Chris Lattner4b2ff022007-09-21 18:15:22 +0000559/// CmpCaseVals - Comparison predicate for sorting case values.
560///
561static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
562 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
563 if (lhs.first < rhs.first)
564 return true;
565
566 if (lhs.first == rhs.first &&
567 lhs.second->getCaseLoc().getRawEncoding()
568 < rhs.second->getCaseLoc().getRawEncoding())
569 return true;
570 return false;
571}
572
Douglas Gregorbd6839732010-02-08 22:24:16 +0000573/// CmpEnumVals - Comparison predicate for sorting enumeration values.
574///
575static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
576 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
577{
578 return lhs.first < rhs.first;
579}
580
581/// EqEnumVals - Comparison preficate for uniqing enumeration values.
582///
583static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
584 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
585{
586 return lhs.first == rhs.first;
587}
588
Chris Lattnera96d4272009-10-16 16:45:22 +0000589/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
590/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000591static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
592 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
593 expr = cleanups->getSubExpr();
594 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
595 if (impcast->getCastKind() != CK_IntegralCast) break;
596 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000597 }
598 return expr->getType();
599}
600
John McCalldadc5752010-08-24 06:29:42 +0000601StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000603 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000604 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000605
Craig Topperc3ec1492014-05-26 06:22:03 +0000606 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000607 if (CondVar) {
608 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000609 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
610 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000611 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000612
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000613 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
John McCallb268a282010-08-23 23:25:46 +0000616 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000617 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000618
Douglas Gregore2b37442012-05-04 22:38:52 +0000619 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
620 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000621
Douglas Gregore2b37442012-05-04 22:38:52 +0000622 public:
623 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000624 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
625 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000626
Craig Toppere14c0f82014-03-12 04:55:44 +0000627 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
628 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000629 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
630 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000631
Craig Toppere14c0f82014-03-12 04:55:44 +0000632 SemaDiagnosticBuilder diagnoseIncomplete(
633 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000634 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
635 << T << Cond->getSourceRange();
636 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000637
Craig Toppere14c0f82014-03-12 04:55:44 +0000638 SemaDiagnosticBuilder diagnoseExplicitConv(
639 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000640 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
641 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000642
Craig Toppere14c0f82014-03-12 04:55:44 +0000643 SemaDiagnosticBuilder noteExplicitConv(
644 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000645 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
646 << ConvTy->isEnumeralType() << ConvTy;
647 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000648
Craig Toppere14c0f82014-03-12 04:55:44 +0000649 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
650 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000651 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
652 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000653
Craig Toppere14c0f82014-03-12 04:55:44 +0000654 SemaDiagnosticBuilder noteAmbiguous(
655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000656 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
657 << ConvTy->isEnumeralType() << ConvTy;
658 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000659
Craig Toppere14c0f82014-03-12 04:55:44 +0000660 SemaDiagnosticBuilder diagnoseConversion(
661 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000662 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000663 }
664 } SwitchDiagnoser(Cond);
665
Richard Smithccc11812013-05-21 19:05:48 +0000666 CondResult =
667 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000668 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000669 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000670
John McCall5939b162011-08-06 07:30:58 +0000671 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
672 CondResult = UsualUnaryConversions(Cond);
673 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000674 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000675
Meador Ingef0af05c2015-06-25 22:06:40 +0000676 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
677 if (CondResult.isInvalid())
678 return StmtError();
679 Cond = CondResult.get();
John McCalla95172b2010-08-01 00:26:45 +0000680
John McCallaab3e412010-08-25 08:40:02 +0000681 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
John McCallb268a282010-08-23 23:25:46 +0000683 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000684 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000685 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000686}
687
Gabor Greif16e02862010-10-01 22:05:14 +0000688static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000689 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000690 Val.setIsSigned(IsSigned);
691}
692
Richard Smith077d0832014-08-04 00:40:48 +0000693/// Check the specified case value is in range for the given unpromoted switch
694/// type.
695static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
696 unsigned UnpromotedWidth, bool UnpromotedSign) {
697 // If the case value was signed and negative and the switch expression is
698 // unsigned, don't bother to warn: this is implementation-defined behavior.
699 // FIXME: Introduce a second, default-ignored warning for this case?
700 if (UnpromotedWidth < Val.getBitWidth()) {
701 llvm::APSInt ConvVal(Val);
702 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
703 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
704 // FIXME: Use different diagnostics for overflow in conversion to promoted
705 // type versus "switch expression cannot have this value". Use proper
706 // IntRange checking rather than just looking at the unpromoted type here.
707 if (ConvVal != Val)
708 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
709 << ConvVal.toString(10);
710 }
711}
712
Alexis Hunt724f14e2014-11-28 00:53:20 +0000713typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
714
Dmitri Gribenko58683752013-12-05 22:52:07 +0000715/// Returns true if we should emit a diagnostic about this case expression not
716/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000717static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000718 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000719 const Expr *CaseExpr,
720 EnumValsTy::iterator &EI,
721 EnumValsTy::iterator &EIEnd,
722 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000723 if (const DeclRefExpr *DRE =
724 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000725 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000726 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000727 QualType EnumType = S.Context.getTypeDeclType(ED);
728 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
729 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000730 return false;
731 }
732 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000733
Richard Smith332653c2015-09-04 01:03:03 +0000734 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000735 return !S.IsValueInFlagEnum(ED, Val, false);
736 } else {
737 while (EI != EIEnd && EI->first < Val)
738 EI++;
739
740 if (EI != EIEnd && EI->first == Val)
741 return false;
742 }
743
Dmitri Gribenko58683752013-12-05 22:52:07 +0000744 return true;
745}
746
John McCalldadc5752010-08-24 06:29:42 +0000747StmtResult
John McCallb268a282010-08-23 23:25:46 +0000748Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
749 Stmt *BodyStmt) {
750 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000751 assert(SS == getCurFunction()->SwitchStack.back() &&
752 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000753
David Majnemer418ad3f2014-12-15 07:46:12 +0000754 getCurFunction()->SwitchStack.pop_back();
755
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000756 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000757 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000758
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000759 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000760 if (!CondExpr) return StmtError();
761
762 QualType CondType = CondExpr->getType();
763
John McCalld3dfbd62010-05-18 03:19:21 +0000764 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000765 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000766 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000767
Chris Lattnera96d4272009-10-16 16:45:22 +0000768 // C++ 6.4.2.p2:
769 // Integral promotions are performed (on the switch condition).
770 //
771 // A case value unrepresentable by the original switch condition
772 // type (before the promotion) doesn't make sense, even when it can
773 // be represented by the promoted type. Therefore we need to find
774 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000775 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000776 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000778 // appropriate type now, just return an error.
779 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000780 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000781
Chris Lattner4ebae652010-04-16 23:34:13 +0000782 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000783 // switch(bool_expr) {...} is often a programmer error, e.g.
784 // switch(n && mask) { ... } // Doh - should be "n & mask".
785 // One can always use an if statement instead of switch(bool_expr).
786 Diag(SwitchLoc, diag::warn_bool_switch_condition)
787 << CondExpr->getSourceRange();
788 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000789 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000790
Richard Smith077d0832014-08-04 00:40:48 +0000791 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000792 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000793 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000794 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000795 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
796 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
797
798 // Get the width and signedness that the condition might actually have, for
799 // warning purposes.
800 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
801 // type.
802 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000803 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000804 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000805 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000807 // Accumulate all of the case values in a vector so that we can sort them
808 // and detect duplicates. This vector contains the APInt for the case after
809 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000810 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000811 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000813 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000814 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
815 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000816
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000818
Chris Lattner10cb5e52007-08-23 06:23:56 +0000819 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000820
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000821 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000822 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000823
Anders Carlsson51873c22007-07-22 07:07:56 +0000824 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000825 if (TheDefaultStmt) {
826 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000827 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000828
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000829 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000830 // we'll return a valid AST. This requires recursing down the AST and
831 // finding it, not something we are set up to do right now. For now,
832 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000833 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000834 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000835 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000837 } else {
838 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattnera65e1f32008-01-16 19:17:22 +0000840 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000841
842 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
843 HasDependentValue = true;
844 break;
845 }
Mike Stump11289f42009-09-09 15:08:12 +0000846
Richard Smithf8379a02012-01-18 23:55:52 +0000847 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000849 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000850 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
851 // constant expression of the promoted type of the switch condition.
852 ExprResult ConvLo =
853 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
854 if (ConvLo.isInvalid()) {
855 CaseListIsErroneous = true;
856 continue;
857 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000858 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000859 } else {
860 // We already verified that the expression has a i-c-e value (C99
861 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000862 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000863
864 // If the LHS is not the same type as the condition, insert an implicit
865 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000866 Lo = DefaultLvalueConversion(Lo).get();
867 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000868 }
869
Richard Smith077d0832014-08-04 00:40:48 +0000870 // Check the unconverted value is within the range of possible values of
871 // the switch expression.
872 checkCaseValue(*this, Lo->getLocStart(), LoVal,
873 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
874
875 // Convert the value to the same width/sign as the condition.
876 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000877
Chris Lattnera65e1f32008-01-16 19:17:22 +0000878 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner10cb5e52007-08-23 06:23:56 +0000880 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000881 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000882 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000883 CS->getRHS()->isValueDependent()) {
884 HasDependentValue = true;
885 break;
886 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000887 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000888 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000889 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000890 }
891 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000892
893 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000894 // If we don't have a default statement, check whether the
895 // condition is constant.
896 llvm::APSInt ConstantCondValue;
897 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000898 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000899 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
900 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000901 assert(!HasConstantCond ||
902 (ConstantCondValue.getBitWidth() == CondWidth &&
903 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000904 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000905 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000906
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000907 // Sort all the scalar case values so we can easily detect duplicates.
908 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
909
910 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000911 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
912 if (ShouldCheckConstantCond &&
913 CaseVals[i].first == ConstantCondValue)
914 ShouldCheckConstantCond = false;
915
916 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000917 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000918 // First, determine if either case value has a name
919 StringRef PrevString, CurrString;
920 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
921 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
922 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
923 PrevString = DeclRef->getDecl()->getName();
924 }
925 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
926 CurrString = DeclRef->getDecl()->getName();
927 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000928 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000929 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000930
931 if (PrevString == CurrString)
932 Diag(CaseVals[i].second->getLHS()->getLocStart(),
933 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000934 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000935 else
936 Diag(CaseVals[i].second->getLHS()->getLocStart(),
937 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000938 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
939 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000940 CaseValStr;
941
John McCalld3dfbd62010-05-18 03:19:21 +0000942 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000944 // FIXME: We really want to remove the bogus case stmt from the
945 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000946 CaseListIsErroneous = true;
947 }
948 }
949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000951 // Detect duplicate case ranges, which usually don't exist at all in
952 // the first place.
953 if (!CaseRanges.empty()) {
954 // Sort all the case ranges by their low value so we can easily detect
955 // overlaps between ranges.
956 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000958 // Scan the ranges, computing the high values and removing empty ranges.
959 std::vector<llvm::APSInt> HiVals;
960 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000961 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000962 CaseStmt *CR = CaseRanges[i].second;
963 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000964 llvm::APSInt HiVal;
965
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000966 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000967 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
968 // constant expression of the promoted type of the switch condition.
969 ExprResult ConvHi =
970 CheckConvertedConstantExpression(Hi, CondType, HiVal,
971 CCEK_CaseValue);
972 if (ConvHi.isInvalid()) {
973 CaseListIsErroneous = true;
974 continue;
975 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000976 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000977 } else {
978 HiVal = Hi->EvaluateKnownConstInt(Context);
979
980 // If the RHS is not the same type as the condition, insert an
981 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000982 Hi = DefaultLvalueConversion(Hi).get();
983 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Richard Smith077d0832014-08-04 00:40:48 +0000986 // Check the unconverted value is within the range of possible values of
987 // the switch expression.
988 checkCaseValue(*this, Hi->getLocStart(), HiVal,
989 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
990
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000991 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000992 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000994 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000996 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000997 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000998 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
999 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +00001000 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001001 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001002 --i;
1003 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001004 continue;
1005 }
John McCalld3dfbd62010-05-18 03:19:21 +00001006
1007 if (ShouldCheckConstantCond &&
1008 LoVal <= ConstantCondValue &&
1009 ConstantCondValue <= HiVal)
1010 ShouldCheckConstantCond = false;
1011
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001012 HiVals.push_back(HiVal);
1013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001015 // Rescan the ranges, looking for overlap with singleton values and other
1016 // ranges. Since the range list is sorted, we only need to compare case
1017 // ranges with their neighbors.
1018 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1019 llvm::APSInt &CRLo = CaseRanges[i].first;
1020 llvm::APSInt &CRHi = HiVals[i];
1021 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001022
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001023 // Check to see whether the case range overlaps with any
1024 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001025 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001026 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001027
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001028 // Find the smallest value >= the lower bound. If I is in the
1029 // case range, then we have overlap.
1030 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1031 CaseVals.end(), CRLo,
1032 CaseCompareFunctor());
1033 if (I != CaseVals.end() && I->first < CRHi) {
1034 OverlapVal = I->first; // Found overlap with scalar.
1035 OverlapStmt = I->second;
1036 }
Mike Stump11289f42009-09-09 15:08:12 +00001037
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001038 // Find the smallest value bigger than the upper bound.
1039 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1040 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1041 OverlapVal = (I-1)->first; // Found overlap with scalar.
1042 OverlapStmt = (I-1)->second;
1043 }
Mike Stump11289f42009-09-09 15:08:12 +00001044
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001045 // Check to see if this case stmt overlaps with the subsequent
1046 // case range.
1047 if (i && CRLo <= HiVals[i-1]) {
1048 OverlapVal = HiVals[i-1]; // Found overlap with range.
1049 OverlapStmt = CaseRanges[i-1].second;
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001052 if (OverlapStmt) {
1053 // If we have a duplicate, report it.
1054 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1055 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001056 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001057 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001058 // FIXME: We really want to remove the bogus case stmt from the
1059 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001060 CaseListIsErroneous = true;
1061 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001062 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001063 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001064
John McCalld3dfbd62010-05-18 03:19:21 +00001065 // Complain if we have a constant condition and we didn't find a match.
1066 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1067 // TODO: it would be nice if we printed enums as enums, chars as
1068 // chars, etc.
1069 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1070 << ConstantCondValue.toString(10)
1071 << CondExpr->getSourceRange();
1072 }
1073
1074 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001075 // values. We only issue a warning if there is not 'default:', but
1076 // we still do the analysis to preserve this information in the AST
1077 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001078 //
Chris Lattner51679082010-09-16 17:09:42 +00001079 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001080
Douglas Gregorbd6839732010-02-08 22:24:16 +00001081 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001082 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001083 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001084 EnumValsTy EnumVals;
1085
John McCalld3dfbd62010-05-18 03:19:21 +00001086 // Gather all enum values, set their type and sort them,
1087 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001088 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001089 llvm::APSInt Val = EDI->getInitVal();
1090 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001091 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001092 }
1093 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001094 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001095 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001096
1097 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001098 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001099 CI != CaseVals.end(); CI++) {
1100 Expr *CaseExpr = CI->second->getLHS();
1101 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1102 CI->first))
1103 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1104 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001105 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001106
David Blaikiee476f972012-01-22 02:31:55 +00001107 // See which of case ranges aren't in enum
1108 EI = EnumVals.begin();
1109 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001110 RI != CaseRanges.end(); RI++) {
1111 Expr *CaseExpr = RI->second->getLHS();
1112 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1113 RI->first))
1114 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1115 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001116
Chad Rosier02a84392012-08-10 17:56:09 +00001117 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001118 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1119 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001120
1121 CaseExpr = RI->second->getRHS();
1122 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1123 Hi))
1124 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1125 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001127
Ted Kremenekc42f3452010-09-09 00:05:53 +00001128 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001129 auto CI = CaseVals.begin();
1130 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001131 bool hasCasesNotInSwitch = false;
1132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001133 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
Alexis Hunt724f14e2014-11-28 00:53:20 +00001135 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001136 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001137 while (CI != CaseVals.end() && CI->first < EI->first)
1138 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139
Douglas Gregorbd6839732010-02-08 22:24:16 +00001140 if (CI != CaseVals.end() && CI->first == EI->first)
1141 continue;
1142
Ted Kremenekc42f3452010-09-09 00:05:53 +00001143 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001144 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001145 llvm::APSInt Hi =
1146 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001147 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001148 if (EI->first <= Hi)
1149 break;
1150 }
1151
Ted Kremenekc42f3452010-09-09 00:05:53 +00001152 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001153 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001154 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001155 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001157
David Blaikie60ac6382012-01-23 04:46:12 +00001158 if (TheDefaultStmt && UnhandledNames.empty())
1159 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001160
Chris Lattner51679082010-09-16 17:09:42 +00001161 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001162 if (!UnhandledNames.empty()) {
1163 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1164 TheDefaultStmt ? diag::warn_def_missing_case
1165 : diag::warn_missing_case)
1166 << (int)UnhandledNames.size();
1167
1168 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1169 I != E; ++I)
1170 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001171 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001172
1173 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001174 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001175 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001176 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001177
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001178 if (BodyStmt)
1179 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1180 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001181
Mike Stump87c57ac2009-05-16 07:39:55 +00001182 // FIXME: If the case list was broken is some way, we don't have a good system
1183 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001184 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001185 return StmtError();
1186
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001187 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001188}
1189
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001190void
1191Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1192 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001193 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001194 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001195
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001196 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001197 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001198 SrcType->isIntegerType()) {
1199 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1200 SrcExpr->isIntegerConstantExpr(Context)) {
1201 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001202 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001203 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1204
1205 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001206 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001207 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001208
Alexis Hunt724f14e2014-11-28 00:53:20 +00001209 if (ED->hasAttr<FlagEnumAttr>()) {
1210 if (!IsValueInFlagEnum(ED, RhsVal, true))
1211 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001212 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001213 } else {
1214 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1215 EnumValsTy;
1216 EnumValsTy EnumVals;
1217
1218 // Gather all enum values, set their type and sort them,
1219 // allowing easier comparison with rhs constant.
1220 for (auto *EDI : ED->enumerators()) {
1221 llvm::APSInt Val = EDI->getInitVal();
1222 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1223 EnumVals.push_back(std::make_pair(Val, EDI));
1224 }
1225 if (EnumVals.empty())
1226 return;
1227 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1228 EnumValsTy::iterator EIend =
1229 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1230
1231 // See which values aren't in the enum.
1232 EnumValsTy::const_iterator EI = EnumVals.begin();
1233 while (EI != EIend && EI->first < RhsVal)
1234 EI++;
1235 if (EI == EIend || EI->first != RhsVal) {
1236 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1237 << DstType.getUnqualifiedType();
1238 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001239 }
1240 }
1241 }
1242}
1243
John McCalldadc5752010-08-24 06:29:42 +00001244StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001246 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001247 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248
Craig Topperc3ec1492014-05-26 06:22:03 +00001249 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001250 if (CondVar) {
1251 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001252 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001253 CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001254 if (CondResult.isInvalid())
1255 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001256 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001257 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001258 if (!ConditionExpr)
1259 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001260 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261
Richard Trieufaca2d82016-02-18 23:58:40 +00001262 if (ConditionExpr &&
1263 !Diags.isIgnored(diag::warn_comma_operator, ConditionExpr->getExprLoc()))
1264 CommaVisitor(*this).Visit(ConditionExpr);
1265
John McCallb268a282010-08-23 23:25:46 +00001266 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001267
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001268 if (isa<NullStmt>(Body))
1269 getCurCompoundScope().setHasEmptyLoopBodies();
1270
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001271 return new (Context)
1272 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001273}
1274
John McCalldadc5752010-08-24 06:29:42 +00001275StmtResult
John McCallb268a282010-08-23 23:25:46 +00001276Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001277 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001278 Expr *Cond, SourceLocation CondRParen) {
1279 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001280
Serge Pavlov09f99242014-01-23 15:05:00 +00001281 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001282 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001283 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001284 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001285 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001286
Richard Smith945f8d32013-01-14 22:39:08 +00001287 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001288 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001289 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001290 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001291
John McCallb268a282010-08-23 23:25:46 +00001292 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001294 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001295}
1296
Richard Trieu451a5db2012-04-30 18:01:30 +00001297namespace {
1298 // This visitor will traverse a conditional statement and store all
1299 // the evaluated decls into a vector. Simple is set to true if none
1300 // of the excluded constructs are used.
1301 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001302 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001303 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001304 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001305 public:
1306 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001307
Craig Topper4dd9b432014-08-17 23:49:53 +00001308 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001309 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001310 Inherited(S.Context),
1311 Decls(Decls),
1312 Ranges(Ranges),
1313 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001314
Richard Trieu9d228802013-05-31 22:46:45 +00001315 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001316
Richard Trieu9d228802013-05-31 22:46:45 +00001317 // Replaces the method in EvaluatedExprVisitor.
1318 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001319 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001320 }
1321
1322 // Any Stmt not whitelisted will cause the condition to be marked complex.
1323 void VisitStmt(Stmt *S) {
1324 Simple = false;
1325 }
1326
1327 void VisitBinaryOperator(BinaryOperator *E) {
1328 Visit(E->getLHS());
1329 Visit(E->getRHS());
1330 }
1331
1332 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001333 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001334 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001335
Richard Trieu9d228802013-05-31 22:46:45 +00001336 void VisitUnaryOperator(UnaryOperator *E) {
1337 // Skip checking conditionals with derefernces.
1338 if (E->getOpcode() == UO_Deref)
1339 Simple = false;
1340 else
1341 Visit(E->getSubExpr());
1342 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001343
Richard Trieu9d228802013-05-31 22:46:45 +00001344 void VisitConditionalOperator(ConditionalOperator *E) {
1345 Visit(E->getCond());
1346 Visit(E->getTrueExpr());
1347 Visit(E->getFalseExpr());
1348 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001349
Richard Trieu9d228802013-05-31 22:46:45 +00001350 void VisitParenExpr(ParenExpr *E) {
1351 Visit(E->getSubExpr());
1352 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001353
Richard Trieu9d228802013-05-31 22:46:45 +00001354 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1355 Visit(E->getOpaqueValue()->getSourceExpr());
1356 Visit(E->getFalseExpr());
1357 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
Richard Trieu9d228802013-05-31 22:46:45 +00001359 void VisitIntegerLiteral(IntegerLiteral *E) { }
1360 void VisitFloatingLiteral(FloatingLiteral *E) { }
1361 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1362 void VisitCharacterLiteral(CharacterLiteral *E) { }
1363 void VisitGNUNullExpr(GNUNullExpr *E) { }
1364 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 void VisitDeclRefExpr(DeclRefExpr *E) {
1367 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1368 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001369
Richard Trieu9d228802013-05-31 22:46:45 +00001370 Ranges.push_back(E->getSourceRange());
1371
1372 Decls.insert(VD);
1373 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001374
1375 }; // end class DeclExtractor
1376
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001377 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001378 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001379 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001380 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001381 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001382
Richard Trieu9d228802013-05-31 22:46:45 +00001383 public:
1384 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001385
Craig Topper4dd9b432014-08-17 23:49:53 +00001386 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001387 Stmt *Statement) :
1388 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1389 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001390
Richard Trieu9d228802013-05-31 22:46:45 +00001391 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001392 }
1393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 void VisitReturnStmt(ReturnStmt *S) {
1395 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001396 }
1397
Richard Trieu9d228802013-05-31 22:46:45 +00001398 void VisitBreakStmt(BreakStmt *S) {
1399 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001400 }
1401
Richard Trieu9d228802013-05-31 22:46:45 +00001402 void VisitGotoStmt(GotoStmt *S) {
1403 FoundDecl = true;
1404 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001405
Richard Trieu9d228802013-05-31 22:46:45 +00001406 void VisitCastExpr(CastExpr *E) {
1407 if (E->getCastKind() == CK_LValueToRValue)
1408 CheckLValueToRValueCast(E->getSubExpr());
1409 else
1410 Visit(E->getSubExpr());
1411 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001412
Richard Trieu9d228802013-05-31 22:46:45 +00001413 void CheckLValueToRValueCast(Expr *E) {
1414 E = E->IgnoreParenImpCasts();
1415
1416 if (isa<DeclRefExpr>(E)) {
1417 return;
1418 }
1419
1420 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1421 Visit(CO->getCond());
1422 CheckLValueToRValueCast(CO->getTrueExpr());
1423 CheckLValueToRValueCast(CO->getFalseExpr());
1424 return;
1425 }
1426
1427 if (BinaryConditionalOperator *BCO =
1428 dyn_cast<BinaryConditionalOperator>(E)) {
1429 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1430 CheckLValueToRValueCast(BCO->getFalseExpr());
1431 return;
1432 }
1433
1434 Visit(E);
1435 }
1436
1437 void VisitDeclRefExpr(DeclRefExpr *E) {
1438 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1439 if (Decls.count(VD))
1440 FoundDecl = true;
1441 }
1442
Steven Wu92910f62016-03-10 02:02:48 +00001443 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1444 // Only need to visit the semantics for POE.
1445 // SyntaticForm doesn't really use the Decal.
1446 for (auto *S : POE->semantics()) {
1447 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1448 // Look past the OVE into the expression it binds.
1449 Visit(OVE->getSourceExpr());
1450 else
1451 Visit(S);
1452 }
1453 }
1454
Richard Trieu9d228802013-05-31 22:46:45 +00001455 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001456
1457 }; // end class DeclMatcher
1458
1459 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1460 Expr *Third, Stmt *Body) {
1461 // Condition is empty
1462 if (!Second) return;
1463
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001464 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1465 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001466 return;
1467
1468 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1469 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001470 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001471 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001472 DE.Visit(Second);
1473
1474 // Don't analyze complex conditionals.
1475 if (!DE.isSimple()) return;
1476
1477 // No decls found.
1478 if (Decls.size() == 0) return;
1479
Richard Trieu0030f1d2012-05-04 03:01:54 +00001480 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001481 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1482 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001483 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001484 if ((*I)->getType().isVolatileQualified() ||
1485 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001486
1487 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1488 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1489 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1490 return;
1491
1492 // Load decl names into diagnostic.
1493 if (Decls.size() > 4)
1494 PDiag << 0;
1495 else {
1496 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001497 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1498 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001499 I != E; ++I)
1500 PDiag << (*I)->getDeclName();
1501 }
1502
1503 // Load SourceRanges into diagnostic if there is room.
1504 // Otherwise, load the SourceRange of the conditional expression.
1505 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001506 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001507 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001508 I != E; ++I)
1509 PDiag << *I;
1510 else
1511 PDiag << Second->getSourceRange();
1512
1513 S.Diag(Ranges.begin()->getBegin(), PDiag);
1514 }
1515
Richard Trieu4e7c9622013-08-06 21:31:54 +00001516 // If Statement is an incemement or decrement, return true and sets the
1517 // variables Increment and DRE.
1518 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1519 DeclRefExpr *&DRE) {
1520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1521 switch (UO->getOpcode()) {
1522 default: return false;
1523 case UO_PostInc:
1524 case UO_PreInc:
1525 Increment = true;
1526 break;
1527 case UO_PostDec:
1528 case UO_PreDec:
1529 Increment = false;
1530 break;
1531 }
1532 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1533 return DRE;
1534 }
1535
1536 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1537 FunctionDecl *FD = Call->getDirectCallee();
1538 if (!FD || !FD->isOverloadedOperator()) return false;
1539 switch (FD->getOverloadedOperator()) {
1540 default: return false;
1541 case OO_PlusPlus:
1542 Increment = true;
1543 break;
1544 case OO_MinusMinus:
1545 Increment = false;
1546 break;
1547 }
1548 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1549 return DRE;
1550 }
1551
1552 return false;
1553 }
1554
Serge Pavlov09f99242014-01-23 15:05:00 +00001555 // A visitor to determine if a continue or break statement is a
1556 // subexpression.
1557 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1558 SourceLocation BreakLoc;
1559 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001560 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001561 BreakContinueFinder(Sema &S, Stmt* Body) :
1562 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001563 Visit(Body);
1564 }
1565
Serge Pavlov09f99242014-01-23 15:05:00 +00001566 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001567
1568 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001569 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001570 }
1571
Serge Pavlov09f99242014-01-23 15:05:00 +00001572 void VisitBreakStmt(BreakStmt* E) {
1573 BreakLoc = E->getBreakLoc();
1574 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001575
Serge Pavlov09f99242014-01-23 15:05:00 +00001576 bool ContinueFound() { return ContinueLoc.isValid(); }
1577 bool BreakFound() { return BreakLoc.isValid(); }
1578 SourceLocation GetContinueLoc() { return ContinueLoc; }
1579 SourceLocation GetBreakLoc() { return BreakLoc; }
1580
1581 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001582
1583 // Emit a warning when a loop increment/decrement appears twice per loop
1584 // iteration. The conditions which trigger this warning are:
1585 // 1) The last statement in the loop body and the third expression in the
1586 // for loop are both increment or both decrement of the same variable
1587 // 2) No continue statements in the loop body.
1588 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1589 // Return when there is nothing to check.
1590 if (!Body || !Third) return;
1591
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001592 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1593 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001594 return;
1595
1596 // Get the last statement from the loop body.
1597 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1598 if (!CS || CS->body_empty()) return;
1599 Stmt *LastStmt = CS->body_back();
1600 if (!LastStmt) return;
1601
1602 bool LoopIncrement, LastIncrement;
1603 DeclRefExpr *LoopDRE, *LastDRE;
1604
1605 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1606 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1607
1608 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001609 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001610 if (LoopIncrement != LastIncrement ||
1611 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1612
Serge Pavlov09f99242014-01-23 15:05:00 +00001613 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001614
1615 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1616 << LastDRE->getDecl() << LastIncrement;
1617 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1618 << LoopIncrement;
1619 }
1620
Richard Trieu451a5db2012-04-30 18:01:30 +00001621} // end namespace
1622
Serge Pavlov09f99242014-01-23 15:05:00 +00001623
1624void Sema::CheckBreakContinueBinding(Expr *E) {
1625 if (!E || getLangOpts().CPlusPlus)
1626 return;
1627 BreakContinueFinder BCFinder(*this, E);
1628 Scope *BreakParent = CurScope->getBreakParent();
1629 if (BCFinder.BreakFound() && BreakParent) {
1630 if (BreakParent->getFlags() & Scope::SwitchScope) {
1631 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1632 } else {
1633 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1634 << "break";
1635 }
1636 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1637 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1638 << "continue";
1639 }
1640}
1641
John McCalldadc5752010-08-24 06:29:42 +00001642StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001643Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001644 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001645 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001646 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001648 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001649 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1650 // declare identifiers for objects having storage class 'auto' or
1651 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001652 for (auto *DI : DS->decls()) {
1653 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001654 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001655 VD = nullptr;
1656 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001657 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1658 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001659 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001660 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001661 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001662 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001663
Serge Pavlov09f99242014-01-23 15:05:00 +00001664 CheckBreakContinueBinding(second.get());
1665 CheckBreakContinueBinding(third.get());
1666
Richard Trieu451a5db2012-04-30 18:01:30 +00001667 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001668 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001669
John McCalldadc5752010-08-24 06:29:42 +00001670 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001671 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001672 if (secondVar) {
1673 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001674 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001675 SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001676 if (SecondResult.isInvalid())
1677 return StmtError();
1678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
Richard Trieufaca2d82016-02-18 23:58:40 +00001680 if (SecondResult.get() &&
1681 !Diags.isIgnored(diag::warn_comma_operator,
1682 SecondResult.get()->getExprLoc()))
1683 CommaVisitor(*this).Visit(SecondResult.get());
1684
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001685 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001686
Anders Carlsson1682af52009-08-01 01:39:59 +00001687 DiagnoseUnusedExprResult(First);
1688 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001689 DiagnoseUnusedExprResult(Body);
1690
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001691 if (isa<NullStmt>(Body))
1692 getCurCompoundScope().setHasEmptyLoopBodies();
1693
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001694 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1695 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001696}
1697
John McCall34376a62010-12-04 03:47:34 +00001698/// In an Objective C collection iteration statement:
1699/// for (x in y)
1700/// x can be an arbitrary l-value expression. Bind it up as a
1701/// full-expression.
1702StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001703 // Reduce placeholder expressions here. Note that this rejects the
1704 // use of pseudo-object l-values in this position.
1705 ExprResult result = CheckPlaceholderExpr(E);
1706 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001707 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001708
Richard Smith945f8d32013-01-14 22:39:08 +00001709 ExprResult FullExpr = ActOnFinishFullExpr(E);
1710 if (FullExpr.isInvalid())
1711 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001713}
1714
John McCall53848232011-07-27 01:07:15 +00001715ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001716Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1717 if (!collection)
1718 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001719
Kaelyn Takata15867822014-11-21 18:48:04 +00001720 ExprResult result = CorrectDelayedTyposInExpr(collection);
1721 if (!result.isUsable())
1722 return ExprError();
1723 collection = result.get();
1724
John McCall53848232011-07-27 01:07:15 +00001725 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001726 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001727
1728 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001729 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001730 if (result.isInvalid())
1731 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001732 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001733
1734 // The operand needs to have object-pointer type.
1735 // TODO: should we do a contextual conversion?
1736 const ObjCObjectPointerType *pointerType =
1737 collection->getType()->getAs<ObjCObjectPointerType>();
1738 if (!pointerType)
1739 return Diag(forLoc, diag::err_collection_expr_type)
1740 << collection->getType() << collection->getSourceRange();
1741
1742 // Check that the operand provides
1743 // - countByEnumeratingWithState:objects:count:
1744 const ObjCObjectType *objectType = pointerType->getObjectType();
1745 ObjCInterfaceDecl *iface = objectType->getInterface();
1746
1747 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001748 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001749 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001750 (getLangOpts().ObjCAutoRefCount
1751 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1752 diag::err_arc_collection_forward, collection)
1753 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001754 // Otherwise, if we have any useful type information, check that
1755 // the type declares the appropriate method.
1756 } else if (iface || !objectType->qual_empty()) {
1757 IdentifierInfo *selectorIdents[] = {
1758 &Context.Idents.get("countByEnumeratingWithState"),
1759 &Context.Idents.get("objects"),
1760 &Context.Idents.get("count")
1761 };
1762 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1763
Craig Topperc3ec1492014-05-26 06:22:03 +00001764 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001765
1766 // If there's an interface, look in both the public and private APIs.
1767 if (iface) {
1768 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001769 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001770 }
1771
1772 // Also check protocol qualifiers.
1773 if (!method)
1774 method = LookupMethodInQualifiedType(selector, pointerType,
1775 /*instance*/ true);
1776
1777 // If we didn't find it anywhere, give up.
1778 if (!method) {
1779 Diag(forLoc, diag::warn_collection_expr_type)
1780 << collection->getType() << selector << collection->getSourceRange();
1781 }
1782
1783 // TODO: check for an incompatible signature?
1784 }
1785
1786 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001787 return collection;
John McCall53848232011-07-27 01:07:15 +00001788}
1789
John McCalldadc5752010-08-24 06:29:42 +00001790StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001791Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001792 Stmt *First, Expr *collection,
1793 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001794
1795 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001796 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001797
Fariborz Jahanian93977672008-01-10 20:33:58 +00001798 if (First) {
1799 QualType FirstType;
1800 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001801 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001802 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1803 diag::err_toomany_element_decls));
1804
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001805 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1806 if (!D || D->isInvalidDecl())
1807 return StmtError();
1808
John McCall31168b02011-06-15 23:02:42 +00001809 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001810 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1811 // declare identifiers for objects having storage class 'auto' or
1812 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001813 if (!D->hasLocalStorage())
1814 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001815 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001816
1817 // If the type contained 'auto', deduce the 'auto' to 'id'.
1818 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001819 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1820 VK_RValue);
1821 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001822 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1823 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001824 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001825 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001826 D->setInvalidDecl();
1827 return StmtError();
1828 }
1829
Richard Smith061f1e22013-04-30 21:23:01 +00001830 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001831
1832 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001833 SourceLocation Loc =
1834 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001835 Diag(Loc, diag::warn_auto_var_is_id)
1836 << D->getDeclName();
1837 }
1838 }
1839
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001840 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001841 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001842 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001843 return StmtError(Diag(First->getLocStart(),
1844 diag::err_selector_element_not_lvalue)
1845 << First->getSourceRange());
1846
Mike Stump11289f42009-09-09 15:08:12 +00001847 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001848 if (FirstType.isConstQualified())
1849 Diag(ForLoc, diag::err_selector_element_const_type)
1850 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001851 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001852 if (!FirstType->isDependentType() &&
1853 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001854 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001855 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1856 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001857 }
Chad Rosier02a84392012-08-10 17:56:09 +00001858
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001859 if (CollectionExprResult.isInvalid())
1860 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001861
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001862 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001863 if (CollectionExprResult.isInvalid())
1864 return StmtError();
1865
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001866 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1867 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001868}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001869
Richard Smith02e85f32011-04-14 22:09:26 +00001870/// Finish building a variable declaration for a for-range statement.
1871/// \return true if an error occurs.
1872static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001873 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001874 if (Decl->getType()->isUndeducedType()) {
1875 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1876 if (!Res.isUsable()) {
1877 Decl->setInvalidDecl();
1878 return true;
1879 }
1880 Init = Res.get();
1881 }
1882
Richard Smith02e85f32011-04-14 22:09:26 +00001883 // Deduce the type for the iterator variable now rather than leaving it to
1884 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001885 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001886 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001887 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001888 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001889 SemaRef.Diag(Loc, DiagID) << Init->getType();
1890 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001891 Decl->setInvalidDecl();
1892 return true;
1893 }
Richard Smith061f1e22013-04-30 21:23:01 +00001894 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001895
John McCall31168b02011-06-15 23:02:42 +00001896 // In ARC, infer lifetime.
1897 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1898 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001899 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001900 SemaRef.inferObjCARCLifetime(Decl))
1901 Decl->setInvalidDecl();
1902
Richard Smith02e85f32011-04-14 22:09:26 +00001903 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1904 /*TypeMayContainAuto=*/false);
1905 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001906 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001907 return false;
1908}
1909
Sam Panzer0f384432012-08-21 00:52:01 +00001910namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001911// An enum to represent whether something is dealing with a call to begin()
1912// or a call to end() in a range-based for loop.
1913enum BeginEndFunction {
1914 BEF_begin,
1915 BEF_end
1916};
Sam Panzer0f384432012-08-21 00:52:01 +00001917
Richard Smith02e85f32011-04-14 22:09:26 +00001918/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001919/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001920/// nor from the diagnostics produced when analysing the implicit expressions
1921/// required in a for-range statement.
1922void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001923 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001924 CallExpr *CE = dyn_cast<CallExpr>(E);
1925 if (!CE)
1926 return;
1927 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1928 if (!D)
1929 return;
1930 SourceLocation Loc = D->getLocation();
1931
1932 std::string Description;
1933 bool IsTemplate = false;
1934 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1935 Description = SemaRef.getTemplateArgumentBindingsText(
1936 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1937 IsTemplate = true;
1938 }
1939
1940 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1941 << BEF << IsTemplate << Description << E->getType();
1942}
1943
Sam Panzer0f384432012-08-21 00:52:01 +00001944/// Build a variable declaration for a for-range statement.
1945VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1946 QualType Type, const char *Name) {
1947 DeclContext *DC = SemaRef.CurContext;
1948 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1949 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1950 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001951 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001952 Decl->setImplicit();
1953 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001954}
1955
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001956}
Richard Smith02e85f32011-04-14 22:09:26 +00001957
Fariborz Jahanian00213472012-07-06 19:04:04 +00001958static bool ObjCEnumerationCollection(Expr *Collection) {
1959 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001960 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001961}
1962
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001963/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001964///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001965/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001966/// A range-based for statement is equivalent to
1967///
1968/// {
1969/// auto && __range = range-init;
1970/// for ( auto __begin = begin-expr,
1971/// __end = end-expr;
1972/// __begin != __end;
1973/// ++__begin ) {
1974/// for-range-declaration = *__begin;
1975/// statement
1976/// }
1977/// }
1978///
1979/// The body of the loop is not available yet, since it cannot be analysed until
1980/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001981StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1982 SourceLocation CoawaitLoc, Stmt *First,
1983 SourceLocation ColonLoc, Expr *Range,
1984 SourceLocation RParenLoc,
1985 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001986 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001987 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001988
Richard Smith3249fed2013-08-21 01:40:36 +00001989 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001990 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001991
1992 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1993 assert(DS && "first part of for range not a decl stmt");
1994
1995 if (!DS->isSingleDecl()) {
1996 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1997 return StmtError();
1998 }
Richard Smith02e85f32011-04-14 22:09:26 +00001999
Richard Smith3249fed2013-08-21 01:40:36 +00002000 Decl *LoopVar = DS->getSingleDecl();
2001 if (LoopVar->isInvalidDecl() || !Range ||
2002 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2003 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002004 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002005 }
Richard Smith02e85f32011-04-14 22:09:26 +00002006
Richard Smithcfd53b42015-10-22 06:13:50 +00002007 // Coroutines: 'for co_await' implicitly co_awaits its range.
2008 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002009 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00002010 if (Coawait.isInvalid()) return StmtError();
2011 Range = Coawait.get();
2012 }
2013
Richard Smith02e85f32011-04-14 22:09:26 +00002014 // Build auto && __range = range-init
2015 SourceLocation RangeLoc = Range->getLocStart();
2016 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2017 Context.getAutoRRefDeductType(),
2018 "__range");
2019 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002020 diag::err_for_range_deduction_failure)) {
2021 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002022 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002023 }
Richard Smith02e85f32011-04-14 22:09:26 +00002024
2025 // Claim the type doesn't contain auto: we've already done the checking.
2026 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002027 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00002028 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002029 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002030 if (RangeDecl.isInvalid()) {
2031 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002032 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002033 }
Richard Smith02e85f32011-04-14 22:09:26 +00002034
Richard Smithcfd53b42015-10-22 06:13:50 +00002035 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002036 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2037 /*Cond=*/nullptr, /*Inc=*/nullptr,
2038 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002039}
2040
2041/// \brief Create the initialization, compare, and increment steps for
2042/// the range-based for loop expression.
2043/// This function does not handle array-based for loops,
2044/// which are created in Sema::BuildCXXForRangeStmt.
2045///
2046/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2047/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2048/// CandidateSet and BEF are set and some non-success value is returned on
2049/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002050static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002051 Expr *BeginRange, Expr *EndRange,
2052 QualType RangeType,
2053 VarDecl *BeginVar,
2054 VarDecl *EndVar,
2055 SourceLocation ColonLoc,
2056 OverloadCandidateSet *CandidateSet,
2057 ExprResult *BeginExpr,
2058 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002059 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002060 DeclarationNameInfo BeginNameInfo(
2061 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2062 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2063 ColonLoc);
2064
2065 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2066 Sema::LookupMemberName);
2067 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2068
2069 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2070 // - if _RangeT is a class type, the unqualified-ids begin and end are
2071 // looked up in the scope of class _RangeT as if by class member access
2072 // lookup (3.4.5), and if either (or both) finds at least one
2073 // declaration, begin-expr and end-expr are __range.begin() and
2074 // __range.end(), respectively;
2075 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2076 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2077
2078 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2079 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002080 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002081
2082 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2083 << RangeLoc << BeginRange->getType() << *BEF;
2084 return Sema::FRS_DiagnosticIssued;
2085 }
2086 } else {
2087 // - otherwise, begin-expr and end-expr are begin(__range) and
2088 // end(__range), respectively, where begin and end are looked up with
2089 // argument-dependent lookup (3.4.2). For the purposes of this name
2090 // lookup, namespace std is an associated namespace.
2091
2092 }
2093
Richard Smith9f690bd2015-10-27 06:02:45 +00002094 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002095 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002096 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002097 BeginMemberLookup, CandidateSet,
2098 BeginRange, BeginExpr);
2099
Richard Smith9f690bd2015-10-27 06:02:45 +00002100 if (RangeStatus != Sema::FRS_Success) {
2101 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2102 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2103 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002104 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002105 }
Sam Panzer0f384432012-08-21 00:52:01 +00002106 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2107 diag::err_for_range_iter_deduction_failure)) {
2108 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2109 return Sema::FRS_DiagnosticIssued;
2110 }
2111
Richard Smith9f690bd2015-10-27 06:02:45 +00002112 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002113 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002114 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002115 EndMemberLookup, CandidateSet,
2116 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002117 if (RangeStatus != Sema::FRS_Success) {
2118 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2119 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2120 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002121 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002122 }
Sam Panzer0f384432012-08-21 00:52:01 +00002123 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2124 diag::err_for_range_iter_deduction_failure)) {
2125 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2126 return Sema::FRS_DiagnosticIssued;
2127 }
2128 return Sema::FRS_Success;
2129}
2130
2131/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002132/// If the attempt fails, this function will return a valid, null StmtResult
2133/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002134static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2135 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002136 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002137 Stmt *LoopVarDecl,
2138 SourceLocation ColonLoc,
2139 Expr *Range,
2140 SourceLocation RangeLoc,
2141 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002142 // Determine whether we can rebuild the for-range statement with a
2143 // dereferenced range expression.
2144 ExprResult AdjustedRange;
2145 {
2146 Sema::SFINAETrap Trap(SemaRef);
2147
2148 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2149 if (AdjustedRange.isInvalid())
2150 return StmtResult();
2151
Richard Smith9f690bd2015-10-27 06:02:45 +00002152 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2153 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2154 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002155 if (SR.isInvalid())
2156 return StmtResult();
2157 }
2158
2159 // The attempt to dereference worked well enough that it could produce a valid
2160 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2161 // case there are any other (non-fatal) problems with it.
2162 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2163 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002164 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2165 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002166 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002167}
2168
Richard Smith3249fed2013-08-21 01:40:36 +00002169namespace {
2170/// RAII object to automatically invalidate a declaration if an error occurs.
2171struct InvalidateOnErrorScope {
2172 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2173 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2174 ~InvalidateOnErrorScope() {
2175 if (Enabled && Trap.hasErrorOccurred())
2176 D->setInvalidDecl();
2177 }
2178
2179 DiagnosticErrorTrap Trap;
2180 Decl *D;
2181 bool Enabled;
2182};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002183}
Richard Smith3249fed2013-08-21 01:40:36 +00002184
Richard Smitha05b3b52012-09-20 21:52:32 +00002185/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002186StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002187Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002188 SourceLocation ColonLoc, Stmt *RangeDecl,
2189 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002190 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002191 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002192 // FIXME: This should not be used during template instantiation. We should
2193 // pick up the set of unqualified lookup results for the != and + operators
2194 // in the initial parse.
2195 //
2196 // Testcase (accepts-invalid):
2197 // template<typename T> void f() { for (auto x : T()) {} }
2198 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2199 // bool operator!=(N::X, N::X); void operator++(N::X);
2200 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002201 Scope *S = getCurScope();
2202
2203 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2204 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2205 QualType RangeVarType = RangeVar->getType();
2206
2207 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2208 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2209
Richard Smith3249fed2013-08-21 01:40:36 +00002210 // If we hit any errors, mark the loop variable as invalid if its type
2211 // contains 'auto'.
2212 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2213 LoopVar->getType()->isUndeducedType());
2214
Richard Smith01694c32016-03-20 10:33:40 +00002215 StmtResult BeginDeclStmt = Begin;
2216 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002217 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2218
Richard Smith27d807c2013-04-30 13:56:41 +00002219 if (RangeVarType->isDependentType()) {
2220 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002221 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002222
2223 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2224 // them in properly when we instantiate the loop.
2225 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2226 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Richard Smith01694c32016-03-20 10:33:40 +00002227 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002228 SourceLocation RangeLoc = RangeVar->getLocation();
2229
Ted Kremenekbed648e2011-10-10 22:36:28 +00002230 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2231
2232 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2233 VK_LValue, ColonLoc);
2234 if (BeginRangeRef.isInvalid())
2235 return StmtError();
2236
2237 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2238 VK_LValue, ColonLoc);
2239 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002240 return StmtError();
2241
2242 QualType AutoType = Context.getAutoDeductType();
2243 Expr *Range = RangeVar->getInit();
2244 if (!Range)
2245 return StmtError();
2246 QualType RangeType = Range->getType();
2247
2248 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002249 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002250 return StmtError();
2251
2252 // Build auto __begin = begin-expr, __end = end-expr.
2253 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2254 "__begin");
2255 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2256 "__end");
2257
2258 // Build begin-expr and end-expr and attach to __begin and __end variables.
2259 ExprResult BeginExpr, EndExpr;
2260 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2261 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2262 // __range + __bound, respectively, where __bound is the array bound. If
2263 // _RangeT is an array of unknown size or an array of incomplete type,
2264 // the program is ill-formed;
2265
2266 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002267 BeginExpr = BeginRangeRef;
2268 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002269 diag::err_for_range_iter_deduction_failure)) {
2270 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2271 return StmtError();
2272 }
2273
2274 // Find the array bound.
2275 ExprResult BoundExpr;
2276 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002277 BoundExpr = IntegerLiteral::Create(
2278 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002279 else if (const VariableArrayType *VAT =
2280 dyn_cast<VariableArrayType>(UnqAT))
2281 BoundExpr = VAT->getSizeExpr();
2282 else {
2283 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2284 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002285 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002286 }
2287
2288 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002289 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002290 BoundExpr.get());
2291 if (EndExpr.isInvalid())
2292 return StmtError();
2293 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2294 diag::err_for_range_iter_deduction_failure)) {
2295 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2296 return StmtError();
2297 }
2298 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002299 OverloadCandidateSet CandidateSet(RangeLoc,
2300 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002301 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002302 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002303 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002304 EndRangeRef.get(), RangeType,
2305 BeginVar, EndVar, ColonLoc, &CandidateSet,
2306 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002307
Richard Smitha05b3b52012-09-20 21:52:32 +00002308 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002309 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002310 // If the range is being built from an array parameter, emit a
2311 // a diagnostic that it is being treated as a pointer.
2312 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2313 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2314 QualType ArrayTy = PVD->getOriginalType();
2315 QualType PointerTy = PVD->getType();
2316 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2317 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2318 << RangeLoc << PVD << ArrayTy << PointerTy;
2319 Diag(PVD->getLocation(), diag::note_declared_at);
2320 return StmtError();
2321 }
2322 }
2323 }
2324
2325 // If building the range failed, try dereferencing the range expression
2326 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002327 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002328 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002329 LoopVarDecl, ColonLoc,
2330 Range, RangeLoc,
2331 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002332 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002333 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002334 }
2335
Sam Panzer0f384432012-08-21 00:52:01 +00002336 // Otherwise, emit diagnostics if we haven't already.
2337 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002338 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002339 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2340 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002342 }
2343 // Return an error if no fix was discovered.
2344 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002345 return StmtError();
2346 }
2347
Sam Panzer0f384432012-08-21 00:52:01 +00002348 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2349 "invalid range expression in for loop");
2350
2351 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002352 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002353 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2354 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002355 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2356 ? diag::warn_for_range_begin_end_types_differ
2357 : diag::ext_for_range_begin_end_types_differ)
2358 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002359 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2360 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2361 }
2362
Richard Smith01694c32016-03-20 10:33:40 +00002363 BeginDeclStmt =
2364 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2365 EndDeclStmt =
2366 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002367
Ted Kremenekbed648e2011-10-10 22:36:28 +00002368 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2369 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002370 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002371 if (BeginRef.isInvalid())
2372 return StmtError();
2373
Richard Smith02e85f32011-04-14 22:09:26 +00002374 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2375 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002376 if (EndRef.isInvalid())
2377 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002378
2379 // Build and check __begin != __end expression.
2380 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2381 BeginRef.get(), EndRef.get());
2382 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2383 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2384 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002385 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2386 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002387 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2388 if (!Context.hasSameType(BeginType, EndType))
2389 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2390 return StmtError();
2391 }
2392
2393 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002394 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2395 VK_LValue, ColonLoc);
2396 if (BeginRef.isInvalid())
2397 return StmtError();
2398
Richard Smith02e85f32011-04-14 22:09:26 +00002399 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002400 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002401 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002402 if (!IncrExpr.isInvalid())
2403 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002404 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002405 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2406 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002407 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2408 return StmtError();
2409 }
2410
2411 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002412 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2413 VK_LValue, ColonLoc);
2414 if (BeginRef.isInvalid())
2415 return StmtError();
2416
Richard Smith02e85f32011-04-14 22:09:26 +00002417 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2418 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002419 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2420 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002421 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2422 return StmtError();
2423 }
2424
Richard Smitha05b3b52012-09-20 21:52:32 +00002425 // Attach *__begin as initializer for VD. Don't touch it if we're just
2426 // trying to determine whether this would be a valid range.
2427 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002428 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2429 /*TypeMayContainAuto=*/true);
2430 if (LoopVar->isInvalidDecl())
2431 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2432 }
2433 }
2434
Richard Smitha05b3b52012-09-20 21:52:32 +00002435 // Don't bother to actually allocate the result if we're just trying to
2436 // determine whether it would be valid.
2437 if (Kind == BFRK_Check)
2438 return StmtResult();
2439
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002440 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002441 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2442 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002443 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2444 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002445}
2446
Chad Rosier02a84392012-08-10 17:56:09 +00002447/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002448/// statement.
2449StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2450 if (!S || !B)
2451 return StmtError();
2452 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002453
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002454 ForStmt->setBody(B);
2455 return S;
2456}
2457
Richard Trieu3e1d4832015-04-13 22:08:55 +00002458// Warn when the loop variable is a const reference that creates a copy.
2459// Suggest using the non-reference type for copies. If a copy can be prevented
2460// suggest the const reference type that would do so.
2461// For instance, given "for (const &Foo : Range)", suggest
2462// "for (const Foo : Range)" to denote a copy is made for the loop. If
2463// possible, also suggest "for (const &Bar : Range)" if this type prevents
2464// the copy altogether.
2465static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2466 const VarDecl *VD,
2467 QualType RangeInitType) {
2468 const Expr *InitExpr = VD->getInit();
2469 if (!InitExpr)
2470 return;
2471
2472 QualType VariableType = VD->getType();
2473
2474 const MaterializeTemporaryExpr *MTE =
2475 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2476
2477 // No copy made.
2478 if (!MTE)
2479 return;
2480
2481 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2482
2483 // Searching for either UnaryOperator for dereference of a pointer or
2484 // CXXOperatorCallExpr for handling iterators.
2485 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2486 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2487 E = CCE->getArg(0);
2488 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2489 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2490 E = ME->getBase();
2491 } else {
2492 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2493 E = MTE->GetTemporaryExpr();
2494 }
2495 E = E->IgnoreImpCasts();
2496 }
2497
2498 bool ReturnsReference = false;
2499 if (isa<UnaryOperator>(E)) {
2500 ReturnsReference = true;
2501 } else {
2502 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2503 const FunctionDecl *FD = Call->getDirectCallee();
2504 QualType ReturnType = FD->getReturnType();
2505 ReturnsReference = ReturnType->isReferenceType();
2506 }
2507
2508 if (ReturnsReference) {
2509 // Loop variable creates a temporary. Suggest either to go with
2510 // non-reference loop variable to indiciate a copy is made, or
2511 // the correct time to bind a const reference.
2512 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2513 << VD << VariableType << E->getType();
2514 QualType NonReferenceType = VariableType.getNonReferenceType();
2515 NonReferenceType.removeLocalConst();
2516 QualType NewReferenceType =
2517 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2518 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2519 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2520 } else {
2521 // The range always returns a copy, so a temporary is always created.
2522 // Suggest removing the reference from the loop variable.
2523 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2524 << VD << RangeInitType;
2525 QualType NonReferenceType = VariableType.getNonReferenceType();
2526 NonReferenceType.removeLocalConst();
2527 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2528 << NonReferenceType << VD->getSourceRange();
2529 }
2530}
2531
2532// Warns when the loop variable can be changed to a reference type to
2533// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2534// "for (const Foo &x : Range)" if this form does not make a copy.
2535static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2536 const VarDecl *VD) {
2537 const Expr *InitExpr = VD->getInit();
2538 if (!InitExpr)
2539 return;
2540
2541 QualType VariableType = VD->getType();
2542
2543 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2544 if (!CE->getConstructor()->isCopyConstructor())
2545 return;
2546 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2547 if (CE->getCastKind() != CK_LValueToRValue)
2548 return;
2549 } else {
2550 return;
2551 }
2552
2553 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2554 // should be emitted. Also, only ignore POD types with trivial copy
2555 // constructors.
2556 if (VariableType.isPODType(SemaRef.Context))
2557 return;
2558
2559 // Suggest changing from a const variable to a const reference variable
2560 // if doing so will prevent a copy.
2561 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2562 << VD << VariableType << InitExpr->getType();
2563 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2564 << SemaRef.Context.getLValueReferenceType(VariableType)
2565 << VD->getSourceRange();
2566}
2567
2568/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2569/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2570/// using "const foo x" to show that a copy is made
2571/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2572/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2573/// prevent the copy.
2574/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2575/// Suggest "const foo &x" to prevent the copy.
2576static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2577 const CXXForRangeStmt *ForStmt) {
2578 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2579 ForStmt->getLocStart()) &&
2580 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2581 ForStmt->getLocStart()) &&
2582 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2583 ForStmt->getLocStart())) {
2584 return;
2585 }
2586
2587 const VarDecl *VD = ForStmt->getLoopVariable();
2588 if (!VD)
2589 return;
2590
2591 QualType VariableType = VD->getType();
2592
2593 if (VariableType->isIncompleteType())
2594 return;
2595
2596 const Expr *InitExpr = VD->getInit();
2597 if (!InitExpr)
2598 return;
2599
2600 if (VariableType->isReferenceType()) {
2601 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2602 ForStmt->getRangeInit()->getType());
2603 } else if (VariableType.isConstQualified()) {
2604 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2605 }
2606}
2607
Richard Smith02e85f32011-04-14 22:09:26 +00002608/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2609/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2610/// body cannot be performed until after the type of the range variable is
2611/// determined.
2612StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2613 if (!S || !B)
2614 return StmtError();
2615
Fariborz Jahanian00213472012-07-06 19:04:04 +00002616 if (isa<ObjCForCollectionStmt>(S))
2617 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002618
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002619 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2620 ForStmt->setBody(B);
2621
2622 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2623 diag::warn_empty_range_based_for_body);
2624
Richard Trieu3e1d4832015-04-13 22:08:55 +00002625 DiagnoseForRangeVariableCopies(*this, ForStmt);
2626
Richard Smith02e85f32011-04-14 22:09:26 +00002627 return S;
2628}
2629
Chris Lattnercab02a62011-02-17 20:34:02 +00002630StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2631 SourceLocation LabelLoc,
2632 LabelDecl *TheDecl) {
2633 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002634 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002635 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002636}
Chris Lattner1c310502007-05-31 06:00:00 +00002637
John McCalldadc5752010-08-24 06:29:42 +00002638StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002639Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002640 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002641 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002642 if (!E->isTypeDependent()) {
2643 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002644 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002645 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002646 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002647 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2648 if (ExprRes.isInvalid())
2649 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002650 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002651 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002652 return StmtError();
2653 }
John McCalla95172b2010-08-01 00:26:45 +00002654
Richard Smith945f8d32013-01-14 22:39:08 +00002655 ExprResult ExprRes = ActOnFinishFullExpr(E);
2656 if (ExprRes.isInvalid())
2657 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002658 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002659
John McCallaab3e412010-08-25 08:40:02 +00002660 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002661
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002662 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002663}
2664
Nico Weberd64657f2015-03-09 02:47:59 +00002665static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2666 const Scope &DestScope) {
2667 if (!S.CurrentSEHFinally.empty() &&
2668 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2669 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2670 }
2671}
2672
John McCalldadc5752010-08-24 06:29:42 +00002673StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002674Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002675 Scope *S = CurScope->getContinueParent();
2676 if (!S) {
2677 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002678 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002679 }
Nico Weberd64657f2015-03-09 02:47:59 +00002680 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002681
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002682 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002683}
2684
John McCalldadc5752010-08-24 06:29:42 +00002685StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002686Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002687 Scope *S = CurScope->getBreakParent();
2688 if (!S) {
2689 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002690 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002691 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002692 if (S->isOpenMPLoopScope())
2693 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2694 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002695 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002696
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002697 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002698}
2699
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002701/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002702///
Douglas Gregor5d369002011-01-21 18:05:27 +00002703/// \param ReturnType If we're determining the copy elision candidate for
2704/// a return statement, this is the return type of the function. If we're
2705/// determining the copy elision candidate for a throw expression, this will
2706/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002707///
Douglas Gregor5d369002011-01-21 18:05:27 +00002708/// \param E The expression being returned from the function or block, or
2709/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002710///
Douglas Gregor86394412011-05-20 15:00:53 +00002711/// \param AllowFunctionParameter Whether we allow function parameters to
2712/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2713/// we re-use this logic to determine whether we should try to move as part of
2714/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002715///
2716/// \returns The NRVO candidate variable, if the return statement may use the
2717/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002718VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2719 Expr *E,
2720 bool AllowFunctionParameter) {
2721 if (!getLangOpts().CPlusPlus)
2722 return nullptr;
2723
2724 // - in a return statement in a function [where] ...
2725 // ... the expression is the name of a non-volatile automatic object ...
2726 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002727 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002728 return nullptr;
2729 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2730 if (!VD)
2731 return nullptr;
2732
2733 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2734 return VD;
2735 return nullptr;
2736}
2737
2738bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2739 bool AllowFunctionParameter) {
2740 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002741 // - in a return statement in a function with ...
2742 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002743 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002744 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002745 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002746 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002747 if (!VDType->isDependentType() &&
2748 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2749 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
John McCall03318c12011-11-11 03:57:31 +00002752 // ...object (other than a function or catch-clause parameter)...
2753 if (VD->getKind() != Decl::Var &&
2754 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002755 return false;
2756 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757
John McCall03318c12011-11-11 03:57:31 +00002758 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002759 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002760
2761 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002762 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002763
2764 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002765 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002766
2767 // Variables with higher required alignment than their type's ABI
2768 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002769 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002770 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002771 return false;
John McCall03318c12011-11-11 03:57:31 +00002772
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002773 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002774}
2775
Douglas Gregor626fbed2011-01-21 21:08:57 +00002776/// \brief Perform the initialization of a potentially-movable value, which
2777/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002778///
2779/// This routine implements C++0x [class.copy]p33, which attempts to treat
2780/// returned lvalues as rvalues in certain cases (to prefer move construction),
2781/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002782ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002783Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2784 const VarDecl *NRVOCandidate,
2785 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002786 Expr *Value,
2787 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002788 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789 // When the criteria for elision of a copy operation are met or would
2790 // be met save for the fact that the source object is a function
2791 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002792 // overload resolution to select the constructor for the copy is first
2793 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002794 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002795 if (AllowNRVO &&
2796 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002798 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002799
Douglas Gregorf282a762011-01-21 19:38:21 +00002800 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002802 = InitializationKind::CreateCopy(Value->getLocStart(),
2803 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002804 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
2806 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002807 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002808 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002809 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002810 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002811 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2812 StepEnd = Seq.step_end();
2813 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002814 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002815 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
2817 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002818 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002819
Douglas Gregorf282a762011-01-21 19:38:21 +00002820 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002821 = Constructor->getParamDecl(0)->getType()
2822 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823
Douglas Gregorf282a762011-01-21 19:38:21 +00002824 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002826 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2827 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002828 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
Douglas Gregorf282a762011-01-21 19:38:21 +00002830 // Promote "AsRvalue" to the heap, since we now need this
2831 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002832 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002833 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834
Douglas Gregorf282a762011-01-21 19:38:21 +00002835 // Complete type-checking the initialization of the return type
2836 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002837 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002838 }
2839 }
2840 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
Douglas Gregorf282a762011-01-21 19:38:21 +00002842 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002843 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002844 // (again) now with the return value expression as written.
2845 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002846 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002847
Douglas Gregorf282a762011-01-21 19:38:21 +00002848 return Res;
2849}
2850
Richard Smith4db51c22013-09-25 05:02:54 +00002851/// \brief Determine whether the declared return type of the specified function
2852/// contains 'auto'.
2853static bool hasDeducedReturnType(FunctionDecl *FD) {
2854 const FunctionProtoType *FPT =
2855 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002856 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002857}
2858
Eli Friedman34b49062012-01-26 03:00:14 +00002859/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2860/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002861///
John McCalldadc5752010-08-24 06:29:42 +00002862StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002863Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2864 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002865 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002866 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002867 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002868 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002869
Richard Smith4db51c22013-09-25 05:02:54 +00002870 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2871 // In C++1y, the return type may involve 'auto'.
2872 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2873 FunctionDecl *FD = CurLambda->CallOperator;
2874 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002875 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002876
2877 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2878 assert(AT && "lost auto type from lambda return type");
2879 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2880 FD->setInvalidDecl();
2881 return StmtError();
2882 }
Alp Toker314cc812014-01-25 16:55:45 +00002883 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002884 } else if (CurCap->HasImplicitReturnType) {
2885 // For blocks/lambdas with implicit return types, we check each return
2886 // statement individually, and deduce the common return type when the block
2887 // or lambda is completed.
2888 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002889 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002890 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2891 if (Result.isInvalid())
2892 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002893 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002894
Richard Smith5a0e50c2014-12-19 22:10:51 +00002895 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2896 // when deducing a return type for a lambda-expression (or by extension
2897 // for a block). These rules differ from the stated C++11 rules only in
2898 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002899 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002900 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002901 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002902 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002903 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002904 if (RetValExp) {
2905 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2906 // initializer list, because it is not an expression (even
2907 // though we represent it as one). We still deduce 'void'.
2908 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2909 << RetValExp->getSourceRange();
2910 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002911
Jordan Rosed39e5f12012-07-02 21:19:23 +00002912 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002913 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002914
2915 // Although we'll properly infer the type of the block once it's completed,
2916 // make sure we provide a return type now for better error recovery.
2917 if (CurCap->ReturnType.isNull())
2918 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002919 }
Eli Friedman34b49062012-01-26 03:00:14 +00002920 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002921
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002922 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002923 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2924 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2925 return StmtError();
2926 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002927 } else if (CapturedRegionScopeInfo *CurRegion =
2928 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2929 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2930 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002931 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002932 assert(CurLambda && "unknown kind of captured scope");
2933 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2934 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002935 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2936 return StmtError();
2937 }
2938 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002939
Steve Naroffc540d662008-09-03 18:15:37 +00002940 // Otherwise, verify that this result type matches the previous one. We are
2941 // pickier with blocks than for normal functions because we don't have GCC
2942 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002943 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002944 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002945 // Delay processing for now. TODO: there are lots of dependent
2946 // types we can conclusively prove aren't void.
2947 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002948 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002949 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002950 (RetValExp->isTypeDependent() ||
2951 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002952 if (!getLangOpts().CPlusPlus &&
2953 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002954 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002955 else {
2956 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002957 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002958 }
Steve Naroffc540d662008-09-03 18:15:37 +00002959 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002960 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002961 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2962 } else if (!RetValExp->isTypeDependent()) {
2963 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002964
John McCall5500ef22011-08-17 22:09:46 +00002965 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2966 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2967 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002968
John McCall5500ef22011-08-17 22:09:46 +00002969 // In C++ the return statement is handled via a copy initialization.
2970 // the C version of which boils down to CheckSingleAssignmentConstraints.
2971 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2972 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2973 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002974 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002975 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2976 FnRetType, RetValExp);
2977 if (Res.isInvalid()) {
2978 // FIXME: Cleanup temporaries here, anyway?
2979 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002980 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002981 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002982 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002983 } else {
2984 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002985 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002986
John McCall75f92b52011-08-17 21:34:14 +00002987 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002988 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2989 if (ER.isInvalid())
2990 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002991 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002992 }
John McCall5500ef22011-08-17 22:09:46 +00002993 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2994 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002995
Jordan Rosed39e5f12012-07-02 21:19:23 +00002996 // If we need to check for the named return value optimization,
2997 // or if we need to infer the return type,
2998 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002999 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003000 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003001
Richard Smith9f690bd2015-10-27 06:02:45 +00003002 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3003 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3004
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003005 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003006}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003007
Nico Weber72889432014-09-06 01:25:55 +00003008namespace {
3009/// \brief Marks all typedefs in all local classes in a type referenced.
3010///
3011/// In a function like
3012/// auto f() {
3013/// struct S { typedef int a; };
3014/// return S();
3015/// }
3016///
3017/// the local type escapes and could be referenced in some TUs but not in
3018/// others. Pretend that all local typedefs are always referenced, to not warn
3019/// on this. This isn't necessary if f has internal linkage, or the typedef
3020/// is private.
3021class LocalTypedefNameReferencer
3022 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3023public:
3024 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3025 bool VisitRecordType(const RecordType *RT);
3026private:
3027 Sema &S;
3028};
3029bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3030 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3031 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3032 R->isDependentType())
3033 return true;
3034 for (auto *TmpD : R->decls())
3035 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3036 if (T->getAccess() != AS_private || R->hasFriends())
3037 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3038 return true;
3039}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003040}
Nico Weber72889432014-09-06 01:25:55 +00003041
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003042TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003043 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003044 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3045 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003046 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003047}
3048
Richard Smith2a7d4812013-05-04 07:00:32 +00003049/// Deduce the return type for a function from a returned expression, per
3050/// C++1y [dcl.spec.auto]p6.
3051bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3052 SourceLocation ReturnLoc,
3053 Expr *&RetExpr,
3054 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003055 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003056 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003057
Richard Smithc58f38f2013-08-14 20:16:31 +00003058 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3059 // If the deduction is for a return statement and the initializer is
3060 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003061 Diag(RetExpr->getExprLoc(),
3062 getCurLambda() ? diag::err_lambda_return_init_list
3063 : diag::err_auto_fn_return_init_list)
3064 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003065 return true;
3066 }
3067
3068 if (FD->isDependentContext()) {
3069 // C++1y [dcl.spec.auto]p12:
3070 // Return type deduction [...] occurs when the definition is
3071 // instantiated even if the function body contains a return
3072 // statement with a non-type-dependent operand.
3073 assert(AT->isDeduced() && "should have deduced to dependent type");
3074 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003075 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003076
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003077 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003078 // Otherwise, [...] deduce a value for U using the rules of template
3079 // argument deduction.
3080 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3081
3082 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3083 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3084 << OrigResultType.getType() << RetExpr->getType();
3085
3086 if (DAR != DAR_Succeeded)
3087 return true;
Nico Weber72889432014-09-06 01:25:55 +00003088
3089 // If a local type is part of the returned type, mark its fields as
3090 // referenced.
3091 LocalTypedefNameReferencer Referencer(*this);
3092 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003093 } else {
3094 // In the case of a return with no operand, the initializer is considered
3095 // to be void().
3096 //
3097 // Deduction here can only succeed if the return type is exactly 'cv auto'
3098 // or 'decltype(auto)', so just check for that case directly.
3099 if (!OrigResultType.getType()->getAs<AutoType>()) {
3100 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3101 << OrigResultType.getType();
3102 return true;
3103 }
3104 // We always deduce U = void in this case.
3105 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3106 if (Deduced.isNull())
3107 return true;
3108 }
3109
3110 // If a function with a declared return type that contains a placeholder type
3111 // has multiple return statements, the return type is deduced for each return
3112 // statement. [...] if the type deduced is not the same in each deduction,
3113 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003114 QualType DeducedT = AT->getDeducedType();
3115 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003116 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003117 // It is possible that NewAT->getDeducedType() is null. When that happens,
3118 // we should not crash, instead we ignore this deduction.
3119 if (NewAT->getDeducedType().isNull())
3120 return false;
3121
Douglas Gregora602a152015-10-01 20:20:47 +00003122 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003123 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003124 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3125 NewAT->getDeducedType());
3126 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003127 const LambdaScopeInfo *LambdaSI = getCurLambda();
3128 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3129 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003130 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003131 << true /*IsLambda*/;
3132 } else {
3133 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3134 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003135 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003136 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003137 return true;
3138 }
3139 } else if (!FD->isInvalidDecl()) {
3140 // Update all declarations of the function to have the deduced return type.
3141 Context.adjustDeducedFunctionResultType(FD, Deduced);
3142 }
3143
3144 return false;
3145}
3146
John McCalldadc5752010-08-24 06:29:42 +00003147StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003148Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3149 Scope *CurScope) {
3150 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3151 if (R.isInvalid()) {
3152 return R;
3153 }
3154
3155 if (VarDecl *VD =
3156 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3157 CurScope->addNRVOCandidate(VD);
3158 } else {
3159 CurScope->setNoNRVO();
3160 }
3161
Nico Weberd64657f2015-03-09 02:47:59 +00003162 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3163
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003164 return R;
3165}
3166
3167StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003168 // Check for unexpanded parameter packs.
3169 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3170 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003171
Eli Friedman34b49062012-01-26 03:00:14 +00003172 if (isa<CapturingScopeInfo>(getCurFunction()))
3173 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003174
Chris Lattner79413952008-12-04 23:50:19 +00003175 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003176 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003177 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003178 bool isObjCMethod = false;
3179
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003180 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003181 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003182 if (FD->hasAttrs())
3183 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003184 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003185 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003186 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003187 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003188 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003189 isObjCMethod = true;
3190 if (MD->hasAttrs())
3191 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003192 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3193 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003194 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003195 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003196 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3197 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003198 }
3199 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003200 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003201
Richard Smith2a7d4812013-05-04 07:00:32 +00003202 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3203 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003204 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003205 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3206 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003207 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003208 FD->setInvalidDecl();
3209 return StmtError();
3210 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003211 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003212 }
3213 }
3214 }
3215
Richard Smithc58f38f2013-08-14 20:16:31 +00003216 bool HasDependentReturnType = FnRetType->isDependentType();
3217
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003219 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003220 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003221 if (isa<InitListExpr>(RetValExp)) {
3222 // We simply never allow init lists as the return value of void
3223 // functions. This is compatible because this was never allowed before,
3224 // so there's no legacy code to deal with.
3225 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3226 int FunctionKind = 0;
3227 if (isa<ObjCMethodDecl>(CurDecl))
3228 FunctionKind = 1;
3229 else if (isa<CXXConstructorDecl>(CurDecl))
3230 FunctionKind = 2;
3231 else if (isa<CXXDestructorDecl>(CurDecl))
3232 FunctionKind = 3;
3233
3234 Diag(ReturnLoc, diag::err_return_init_list)
3235 << CurDecl->getDeclName() << FunctionKind
3236 << RetValExp->getSourceRange();
3237
3238 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003239 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003240 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003241 // C99 6.8.6.4p1 (ext_ since GCC warns)
3242 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003243 if (RetValExp->getType()->isVoidType()) {
3244 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3245 if (isa<CXXConstructorDecl>(CurDecl) ||
3246 isa<CXXDestructorDecl>(CurDecl))
3247 D = diag::err_ctor_dtor_returns_void;
3248 else
3249 D = diag::ext_return_has_void_expr;
3250 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003251 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003252 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003253 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003254 if (Result.isInvalid())
3255 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003256 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003257 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003258 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003259 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003260 // return of void in constructor/destructor is illegal in C++.
3261 if (D == diag::err_ctor_dtor_returns_void) {
3262 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3263 Diag(ReturnLoc, D)
3264 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3265 << RetValExp->getSourceRange();
3266 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003267 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003268 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003269 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003270 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003271
3272 int FunctionKind = 0;
3273 if (isa<ObjCMethodDecl>(CurDecl))
3274 FunctionKind = 1;
3275 else if (isa<CXXConstructorDecl>(CurDecl))
3276 FunctionKind = 2;
3277 else if (isa<CXXDestructorDecl>(CurDecl))
3278 FunctionKind = 3;
3279
Nick Lewycky1be750a2011-06-01 07:44:31 +00003280 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003281 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003282 << RetValExp->getSourceRange();
3283 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Sebastian Redleef474c2012-02-22 10:50:08 +00003286 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003287 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3288 if (ER.isInvalid())
3289 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003290 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003291 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293
Craig Topperc3ec1492014-05-26 06:22:03 +00003294 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003295 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003296 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003297
David Majnemer2887ad32014-12-13 08:12:56 +00003298 unsigned DiagID;
3299 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3300 // C++11 [stmt.return]p2
3301 DiagID = diag::err_constexpr_return_missing_expr;
3302 FD->setInvalidDecl();
3303 } else if (getLangOpts().C99) {
3304 // C99 6.8.6.4p1 (ext_ since GCC warns)
3305 DiagID = diag::ext_return_missing_expr;
3306 } else {
3307 // C90 6.6.6.4p4
3308 DiagID = diag::warn_return_missing_expr;
3309 }
3310
3311 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003312 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003313 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003314 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003315
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003316 Result = new (Context) ReturnStmt(ReturnLoc);
3317 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003318 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003319 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003320
3321 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3322
3323 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3324 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3325 // function return.
3326
3327 // In C++ the return statement is handled via a copy initialization,
3328 // the C version of which boils down to CheckSingleAssignmentConstraints.
3329 if (RetValExp)
3330 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003331 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003332 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003334 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003335 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003337 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003338 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003339 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003340 return StmtError();
3341 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003342 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003343
3344 // If we have a related result type, we need to implicitly
3345 // convert back to the formal result type. We can't pretend to
3346 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003347 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003348 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003349 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3350 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003351 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3352 if (Res.isInvalid()) {
3353 // FIXME: Clean up temporaries here anyway?
3354 return StmtError();
3355 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003356 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003357 }
3358
Artyom Skrobov9f213442014-01-24 11:10:39 +00003359 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3360 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
John McCallacf0ee52010-10-08 02:01:28 +00003363 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003364 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3365 if (ER.isInvalid())
3366 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003367 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003368 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003369 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
3372 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003373 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003374 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003375 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003376
Richard Smith9f690bd2015-10-27 06:02:45 +00003377 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3378 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3379
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003380 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003381}
3382
John McCalldadc5752010-08-24 06:29:42 +00003383StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003384Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003385 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003386 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003387 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003388 if (Var && Var->isInvalidDecl())
3389 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003391 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003392}
3393
John McCalldadc5752010-08-24 06:29:42 +00003394StmtResult
John McCallb268a282010-08-23 23:25:46 +00003395Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003396 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003397}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003398
John McCalldadc5752010-08-24 06:29:42 +00003399StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003401 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003402 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003403 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3404
John McCallaab3e412010-08-25 08:40:02 +00003405 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003406 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003407 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3408 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003409}
3410
John McCall0bd3e402012-05-08 21:41:25 +00003411StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003412 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003413 ExprResult Result = DefaultLvalueConversion(Throw);
3414 if (Result.isInvalid())
3415 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003416
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003417 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003418 if (Result.isInvalid())
3419 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003420 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003421
Douglas Gregor2900c162010-04-22 21:44:01 +00003422 QualType ThrowType = Throw->getType();
3423 // Make sure the expression type is an ObjC pointer or "void *".
3424 if (!ThrowType->isDependentType() &&
3425 !ThrowType->isObjCObjectPointerType()) {
3426 const PointerType *PT = ThrowType->getAs<PointerType>();
3427 if (!PT || !PT->getPointeeType()->isVoidType())
3428 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3429 << Throw->getType() << Throw->getSourceRange());
3430 }
3431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003433 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003434}
3435
John McCalldadc5752010-08-24 06:29:42 +00003436StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003438 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003439 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003440 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3441
John McCallb268a282010-08-23 23:25:46 +00003442 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003443 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003444 // in the context of an @catch clause).
3445 Scope *AtCatchParent = CurScope;
3446 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3447 AtCatchParent = AtCatchParent->getParent();
3448 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003449 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 }
John McCallb268a282010-08-23 23:25:46 +00003451 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003452}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003453
John McCalld9bb7432011-07-27 21:50:02 +00003454ExprResult
3455Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3456 ExprResult result = DefaultLvalueConversion(operand);
3457 if (result.isInvalid())
3458 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003459 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003460
3461 // Make sure the expression type is an ObjC pointer or "void *".
3462 QualType type = operand->getType();
3463 if (!type->isDependentType() &&
3464 !type->isObjCObjectPointerType()) {
3465 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003466 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3467 if (getLangOpts().CPlusPlus) {
3468 if (RequireCompleteType(atLoc, type,
3469 diag::err_incomplete_receiver_type))
3470 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3471 << type << operand->getSourceRange();
3472
3473 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3474 if (!result.isUsable())
3475 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3476 << type << operand->getSourceRange();
3477
3478 operand = result.get();
3479 } else {
3480 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3481 << type << operand->getSourceRange();
3482 }
3483 }
John McCalld9bb7432011-07-27 21:50:02 +00003484 }
3485
3486 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003487 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003488}
3489
John McCalldadc5752010-08-24 06:29:42 +00003490StmtResult
John McCallb268a282010-08-23 23:25:46 +00003491Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3492 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003493 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003494 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003495 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003496}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003497
3498/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3499/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003500StmtResult
John McCall48871652010-08-21 09:40:31 +00003501Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003502 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003503 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003504 return new (Context)
3505 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003506}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003507
John McCall31168b02011-06-15 23:02:42 +00003508StmtResult
3509Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3510 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003511 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003512}
3513
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003514namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003515class CatchHandlerType {
3516 QualType QT;
3517 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003518
Aaron Ballman8aee642902015-04-08 00:05:29 +00003519 // This is a special constructor to be used only with DenseMapInfo's
3520 // getEmptyKey() and getTombstoneKey() functions.
3521 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3522 enum Unique { ForDenseMap };
3523 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3524
Sebastian Redl63c4da02009-07-29 17:15:45 +00003525public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003526 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003527 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003528 /// level pointer and cv-qualifiers.
3529 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3530 if (QT->isPointerType())
3531 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003532
Aaron Ballman8aee642902015-04-08 00:05:29 +00003533 if (IsPointer || QT->isReferenceType())
3534 QT = QT->getPointeeType();
3535 QT = QT.getUnqualifiedType();
3536 }
3537
3538 /// Used when creating a CatchHandlerType from a base class type; pretends the
3539 /// type passed in had the pointer qualifier, does not need to get an
3540 /// unqualified type.
3541 CatchHandlerType(QualType QT, bool IsPointer)
3542 : QT(QT), IsPointer(IsPointer) {}
3543
3544 QualType underlying() const { return QT; }
3545 bool isPointer() const { return IsPointer; }
3546
3547 friend bool operator==(const CatchHandlerType &LHS,
3548 const CatchHandlerType &RHS) {
3549 // If the pointer qualification does not match, we can return early.
3550 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003551 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003552 // Otherwise, check the underlying type without cv-qualifiers.
3553 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003554 }
3555};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003556} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003557
Aaron Ballman8aee642902015-04-08 00:05:29 +00003558namespace llvm {
3559template <> struct DenseMapInfo<CatchHandlerType> {
3560 static CatchHandlerType getEmptyKey() {
3561 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3562 CatchHandlerType::ForDenseMap);
3563 }
3564
3565 static CatchHandlerType getTombstoneKey() {
3566 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3567 CatchHandlerType::ForDenseMap);
3568 }
3569
3570 static unsigned getHashValue(const CatchHandlerType &Base) {
3571 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3572 }
3573
3574 static bool isEqual(const CatchHandlerType &LHS,
3575 const CatchHandlerType &RHS) {
3576 return LHS == RHS;
3577 }
3578};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003579}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003580
3581namespace {
3582class CatchTypePublicBases {
3583 ASTContext &Ctx;
3584 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3585 const bool CheckAgainstPointer;
3586
3587 CXXCatchStmt *FoundHandler;
3588 CanQualType FoundHandlerType;
3589
3590public:
3591 CatchTypePublicBases(
3592 ASTContext &Ctx,
3593 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3594 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3595 FoundHandler(nullptr) {}
3596
3597 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3598 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3599
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003600 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003601 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003602 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003603 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003604 auto I = M.find(Check);
3605 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003606 FoundHandler = I->second;
3607 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003608 return true;
3609 }
3610 }
3611 return false;
3612 }
3613};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003614}
Dan Gohman28ade552010-07-26 21:25:24 +00003615
Sebastian Redl9b244a82008-12-22 21:35:02 +00003616/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3617/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003618StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3619 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003620 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003621 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003622 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003623 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003624
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003625 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3626 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3627
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003628 sema::FunctionScopeInfo *FSI = getCurFunction();
3629
Reid Klecknere7175912015-02-02 22:15:31 +00003630 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003631 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003632 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003633 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003634 }
3635
Robert Wilhelmcafda822013-08-22 09:20:03 +00003636 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003637 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003638 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003639
Aaron Ballman8aee642902015-04-08 00:05:29 +00003640 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003641 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003642 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003643
Aaron Ballman8aee642902015-04-08 00:05:29 +00003644 // Diagnose when the handler is a catch-all handler, but it isn't the last
3645 // handler for the try block. [except.handle]p5. Also, skip exception
3646 // declarations that are invalid, since we can't usefully report on them.
3647 if (!H->getExceptionDecl()) {
3648 if (i < NumHandlers - 1)
3649 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003650 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003651 } else if (H->getExceptionDecl()->isInvalidDecl())
3652 continue;
3653
3654 // Walk the type hierarchy to diagnose when this type has already been
3655 // handled (duplication), or cannot be handled (derivation inversion). We
3656 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003657 CatchHandlerType HandlerCHT =
3658 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003659
3660 // We can ignore whether the type is a reference or a pointer; we need the
3661 // underlying declaration type in order to get at the underlying record
3662 // decl, if there is one.
3663 QualType Underlying = HandlerCHT.underlying();
3664 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3665 if (!RD->hasDefinition())
3666 continue;
3667 // Check that none of the public, unambiguous base classes are in the
3668 // map ([except.handle]p1). Give the base classes the same pointer
3669 // qualification as the original type we are basing off of. This allows
3670 // comparison against the handler type using the same top-level pointer
3671 // as the original type.
3672 CXXBasePaths Paths;
3673 Paths.setOrigin(RD);
3674 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003675 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003676 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3677 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3678 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3679 diag::warn_exception_caught_by_earlier_handler)
3680 << H->getCaughtType();
3681 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3682 diag::note_previous_exception_handler)
3683 << Problem->getCaughtType();
3684 }
3685 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003686 }
Mike Stump11289f42009-09-09 15:08:12 +00003687
Aaron Ballman8aee642902015-04-08 00:05:29 +00003688 // Add the type the list of ones we have handled; diagnose if we've already
3689 // handled it.
3690 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3691 if (!R.second) {
3692 const CXXCatchStmt *Problem = R.first->second;
3693 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3694 diag::warn_exception_caught_by_earlier_handler)
3695 << H->getCaughtType();
3696 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3697 diag::note_previous_exception_handler)
3698 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003699 }
3700 }
Mike Stump11289f42009-09-09 15:08:12 +00003701
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003702 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003703
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003704 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003705}
John Wiegley1c0675e2011-04-28 01:08:34 +00003706
Reid Klecknere7175912015-02-02 22:15:31 +00003707StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3708 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003709 assert(TryBlock && Handler);
3710
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003711 sema::FunctionScopeInfo *FSI = getCurFunction();
3712
Reid Klecknere7175912015-02-02 22:15:31 +00003713 // SEH __try is incompatible with C++ try. Borland appears to support this,
3714 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003715 if (!getLangOpts().Borland) {
3716 if (FSI->FirstCXXTryLoc.isValid()) {
3717 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3718 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3719 }
Reid Klecknere7175912015-02-02 22:15:31 +00003720 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003721
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003722 FSI->setHasSEHTry(TryLoc);
3723
3724 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3725 // track if they use SEH.
3726 DeclContext *DC = CurContext;
3727 while (DC && !DC->isFunctionOrMethod())
3728 DC = DC->getParent();
3729 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3730 if (FD)
3731 FD->setUsesSEHTry(true);
3732 else
3733 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003734
Reid Kleckner8819a402015-07-10 00:16:25 +00003735 // Reject __try on unsupported targets.
3736 if (!Context.getTargetInfo().isSEHTrySupported())
3737 Diag(TryLoc, diag::err_seh_try_unsupported);
3738
Reid Klecknere7175912015-02-02 22:15:31 +00003739 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003740}
3741
3742StmtResult
3743Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3744 Expr *FilterExpr,
3745 Stmt *Block) {
3746 assert(FilterExpr && Block);
3747
3748 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003749 return StmtError(Diag(FilterExpr->getExprLoc(),
3750 diag::err_filter_expression_integral)
3751 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003752 }
3753
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003754 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003755}
3756
Nico Weberd64657f2015-03-09 02:47:59 +00003757void Sema::ActOnStartSEHFinallyBlock() {
3758 CurrentSEHFinally.push_back(CurScope);
3759}
3760
Nico Weberce903292015-03-09 03:17:15 +00003761void Sema::ActOnAbortSEHFinallyBlock() {
3762 CurrentSEHFinally.pop_back();
3763}
3764
Nico Weberd64657f2015-03-09 02:47:59 +00003765StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003766 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003767 CurrentSEHFinally.pop_back();
3768 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003769}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003770
Nico Weberc7d05962014-07-06 22:32:59 +00003771StmtResult
3772Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003773 Scope *SEHTryParent = CurScope;
3774 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3775 SEHTryParent = SEHTryParent->getParent();
3776 if (!SEHTryParent)
3777 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003778 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003779
Nico Weber9b982072014-07-07 00:12:30 +00003780 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003781}
3782
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003783StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3784 bool IsIfExists,
3785 NestedNameSpecifierLoc QualifierLoc,
3786 DeclarationNameInfo NameInfo,
3787 Stmt *Nested)
3788{
3789 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003790 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003791 cast<CompoundStmt>(Nested));
3792}
3793
3794
Chad Rosier02a84392012-08-10 17:56:09 +00003795StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003796 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003797 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003798 UnqualifiedId &Name,
3799 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003800 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003801 SS.getWithLocInContext(Context),
3802 GetNameFromUnqualifiedId(Name),
3803 Nested);
3804}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003805
3806RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003807Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3808 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003809 DeclContext *DC = CurContext;
3810 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3811 DC = DC->getParent();
3812
Craig Topperc3ec1492014-05-26 06:22:03 +00003813 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003814 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003815 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3816 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003817 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003818 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003819
Alexey Bataev330de032014-10-29 12:21:55 +00003820 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003821 DC->addDecl(RD);
3822 RD->setImplicit();
3823 RD->startDefinition();
3824
Alexey Bataev9959db52014-05-06 10:08:46 +00003825 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003826 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003827 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003828 return RD;
3829}
3830
3831static void buildCapturedStmtCaptureList(
3832 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3833 SmallVectorImpl<Expr *> &CaptureInits,
3834 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3835
3836 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3837 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3838
3839 if (Cap->isThisCapture()) {
3840 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3841 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003842 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003843 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003844 } else if (Cap->isVLATypeCapture()) {
3845 Captures.push_back(
3846 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3847 CaptureInits.push_back(nullptr);
3848 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003849 }
3850
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003851 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003852 Cap->isReferenceCapture()
3853 ? CapturedStmt::VCK_ByRef
3854 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003855 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003856 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003857 }
3858}
3859
3860void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003861 CapturedRegionKind Kind,
3862 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003863 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003864 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003865
Alexey Bataev9959db52014-05-06 10:08:46 +00003866 // Build the context parameter
3867 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3868 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3869 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3870 ImplicitParamDecl *Param
3871 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3872 DC->addDecl(Param);
3873
3874 CD->setContextParam(0, Param);
3875
3876 // Enter the capturing scope for this captured region.
3877 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3878
3879 if (CurScope)
3880 PushDeclContext(CurScope, CD);
3881 else
3882 CurContext = CD;
3883
3884 PushExpressionEvaluationContext(PotentiallyEvaluated);
3885}
3886
3887void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3888 CapturedRegionKind Kind,
3889 ArrayRef<CapturedParamNameType> Params) {
3890 CapturedDecl *CD = nullptr;
3891 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3892
3893 // Build the context parameter
3894 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3895 bool ContextIsFound = false;
3896 unsigned ParamNum = 0;
3897 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3898 E = Params.end();
3899 I != E; ++I, ++ParamNum) {
3900 if (I->second.isNull()) {
3901 assert(!ContextIsFound &&
3902 "null type has been found already for '__context' parameter");
3903 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3904 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3905 ImplicitParamDecl *Param
3906 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3907 DC->addDecl(Param);
3908 CD->setContextParam(ParamNum, Param);
3909 ContextIsFound = true;
3910 } else {
3911 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3912 ImplicitParamDecl *Param
3913 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3914 DC->addDecl(Param);
3915 CD->setParam(ParamNum, Param);
3916 }
3917 }
3918 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003919 if (!ContextIsFound) {
3920 // Add __context implicitly if it is not specified.
3921 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3922 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3923 ImplicitParamDecl *Param =
3924 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3925 DC->addDecl(Param);
3926 CD->setContextParam(ParamNum, Param);
3927 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003928 // Enter the capturing scope for this captured region.
3929 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3930
3931 if (CurScope)
3932 PushDeclContext(CurScope, CD);
3933 else
3934 CurContext = CD;
3935
3936 PushExpressionEvaluationContext(PotentiallyEvaluated);
3937}
3938
Wei Pan17fbf6e2013-05-04 03:59:06 +00003939void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003940 DiscardCleanupsInEvaluationContext();
3941 PopExpressionEvaluationContext();
3942
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003943 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3944 RecordDecl *Record = RSI->TheRecordDecl;
3945 Record->setInvalidDecl();
3946
Aaron Ballman62e47c42014-03-10 13:43:55 +00003947 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003948 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3949 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003950
Wei Pan17fbf6e2013-05-04 03:59:06 +00003951 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003952 PopFunctionScopeInfo();
3953}
3954
3955StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3956 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3957
3958 SmallVector<CapturedStmt::Capture, 4> Captures;
3959 SmallVector<Expr *, 4> CaptureInits;
3960 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3961
3962 CapturedDecl *CD = RSI->TheCapturedDecl;
3963 RecordDecl *RD = RSI->TheRecordDecl;
3964
Wei Pan17fbf6e2013-05-04 03:59:06 +00003965 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3966 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003967 CaptureInits, CD, RD);
3968
3969 CD->setBody(Res->getCapturedStmt());
3970 RD->completeDefinition();
3971
Wei Pan17fbf6e2013-05-04 03:59:06 +00003972 DiscardCleanupsInEvaluationContext();
3973 PopExpressionEvaluationContext();
3974
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003975 PopDeclContext();
3976 PopFunctionScopeInfo();
3977
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003978 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003979}