blob: 836073a680c17df2cfd1df9e7946166763504396 [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()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +0000252 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
253 if (Func ? Func->hasUnusedResultAttr()
254 : FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000255 Diag(Loc, diag::warn_unused_result) << 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) {
279 if (MD->hasAttr<WarnUnusedResultAttr>()) {
280 Diag(Loc, diag::warn_unused_result) << R1 << R2;
281 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
John McCalldadc5752010-08-24 06:29:42 +0000491StmtResult
John McCall48871652010-08-21 09:40:31 +0000492Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000493 Stmt *thenStmt, SourceLocation ElseLoc,
494 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000495 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000496
Craig Topperc3ec1492014-05-26 06:22:03 +0000497 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000498 if (CondVar) {
499 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000500 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +0000501 CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
Douglas Gregor633caca2009-11-23 23:44:04 +0000502 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000503 Expr *ConditionExpr = CondResult.getAs<Expr>();
Olivier Goffart122993b2015-10-11 17:27:29 +0000504 if (ConditionExpr) {
505 DiagnoseUnusedExprResult(thenStmt);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
Olivier Goffart122993b2015-10-11 17:27:29 +0000507 if (!elseStmt) {
508 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
509 diag::warn_empty_if_body);
510 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000511
Olivier Goffart122993b2015-10-11 17:27:29 +0000512 DiagnoseUnusedExprResult(elseStmt);
513 } else {
514 // Create a dummy Expr for the condition for error recovery
515 ConditionExpr = new (Context) OpaqueValueExpr(SourceLocation(),
516 Context.BoolTy, VK_RValue);
Anders Carlssondb83d772007-10-10 20:50:11 +0000517 }
518
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000519 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
520 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000521}
Steve Naroff86272ea2007-05-29 02:14:17 +0000522
Chris Lattner67998452007-08-23 18:29:20 +0000523namespace {
524 struct CaseCompareFunctor {
525 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
526 const llvm::APSInt &RHS) {
527 return LHS.first < RHS;
528 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000529 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
530 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
531 return LHS.first < RHS.first;
532 }
Chris Lattner67998452007-08-23 18:29:20 +0000533 bool operator()(const llvm::APSInt &LHS,
534 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
535 return LHS < RHS.first;
536 }
537 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000538}
Chris Lattner67998452007-08-23 18:29:20 +0000539
Chris Lattner4b2ff022007-09-21 18:15:22 +0000540/// CmpCaseVals - Comparison predicate for sorting case values.
541///
542static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
543 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
544 if (lhs.first < rhs.first)
545 return true;
546
547 if (lhs.first == rhs.first &&
548 lhs.second->getCaseLoc().getRawEncoding()
549 < rhs.second->getCaseLoc().getRawEncoding())
550 return true;
551 return false;
552}
553
Douglas Gregorbd6839732010-02-08 22:24:16 +0000554/// CmpEnumVals - Comparison predicate for sorting enumeration values.
555///
556static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
557 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
558{
559 return lhs.first < rhs.first;
560}
561
562/// EqEnumVals - Comparison preficate for uniqing enumeration values.
563///
564static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
565 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
566{
567 return lhs.first == rhs.first;
568}
569
Chris Lattnera96d4272009-10-16 16:45:22 +0000570/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
571/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000572static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
573 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
574 expr = cleanups->getSubExpr();
575 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
576 if (impcast->getCastKind() != CK_IntegralCast) break;
577 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000578 }
579 return expr->getType();
580}
581
John McCalldadc5752010-08-24 06:29:42 +0000582StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000584 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000585 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000586
Craig Topperc3ec1492014-05-26 06:22:03 +0000587 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000588 if (CondVar) {
589 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000590 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
591 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000592 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000594 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
John McCallb268a282010-08-23 23:25:46 +0000597 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000598 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
Douglas Gregore2b37442012-05-04 22:38:52 +0000600 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
601 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000602
Douglas Gregore2b37442012-05-04 22:38:52 +0000603 public:
604 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000605 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
606 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000607
Craig Toppere14c0f82014-03-12 04:55:44 +0000608 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
609 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000610 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
611 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000612
Craig Toppere14c0f82014-03-12 04:55:44 +0000613 SemaDiagnosticBuilder diagnoseIncomplete(
614 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000615 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
616 << T << Cond->getSourceRange();
617 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000618
Craig Toppere14c0f82014-03-12 04:55:44 +0000619 SemaDiagnosticBuilder diagnoseExplicitConv(
620 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000621 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
622 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder noteExplicitConv(
625 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
627 << ConvTy->isEnumeralType() << ConvTy;
628 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000629
Craig Toppere14c0f82014-03-12 04:55:44 +0000630 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
631 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000632 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder noteAmbiguous(
636 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000637 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
638 << ConvTy->isEnumeralType() << ConvTy;
639 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000640
Craig Toppere14c0f82014-03-12 04:55:44 +0000641 SemaDiagnosticBuilder diagnoseConversion(
642 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000643 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000644 }
645 } SwitchDiagnoser(Cond);
646
Richard Smithccc11812013-05-21 19:05:48 +0000647 CondResult =
648 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000649 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000650 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000651
John McCall5939b162011-08-06 07:30:58 +0000652 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
653 CondResult = UsualUnaryConversions(Cond);
654 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000655 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000656
Meador Ingef0af05c2015-06-25 22:06:40 +0000657 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
658 if (CondResult.isInvalid())
659 return StmtError();
660 Cond = CondResult.get();
John McCalla95172b2010-08-01 00:26:45 +0000661
John McCallaab3e412010-08-25 08:40:02 +0000662 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
John McCallb268a282010-08-23 23:25:46 +0000664 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000665 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000666 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000667}
668
Gabor Greif16e02862010-10-01 22:05:14 +0000669static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000670 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000671 Val.setIsSigned(IsSigned);
672}
673
Richard Smith077d0832014-08-04 00:40:48 +0000674/// Check the specified case value is in range for the given unpromoted switch
675/// type.
676static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
677 unsigned UnpromotedWidth, bool UnpromotedSign) {
678 // If the case value was signed and negative and the switch expression is
679 // unsigned, don't bother to warn: this is implementation-defined behavior.
680 // FIXME: Introduce a second, default-ignored warning for this case?
681 if (UnpromotedWidth < Val.getBitWidth()) {
682 llvm::APSInt ConvVal(Val);
683 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
684 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
685 // FIXME: Use different diagnostics for overflow in conversion to promoted
686 // type versus "switch expression cannot have this value". Use proper
687 // IntRange checking rather than just looking at the unpromoted type here.
688 if (ConvVal != Val)
689 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
690 << ConvVal.toString(10);
691 }
692}
693
Alexis Hunt724f14e2014-11-28 00:53:20 +0000694typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
695
Dmitri Gribenko58683752013-12-05 22:52:07 +0000696/// Returns true if we should emit a diagnostic about this case expression not
697/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000698static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000699 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000700 const Expr *CaseExpr,
701 EnumValsTy::iterator &EI,
702 EnumValsTy::iterator &EIEnd,
703 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000704 if (const DeclRefExpr *DRE =
705 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000706 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000707 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000708 QualType EnumType = S.Context.getTypeDeclType(ED);
709 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
710 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000711 return false;
712 }
713 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714
Richard Smith332653c2015-09-04 01:03:03 +0000715 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000716 return !S.IsValueInFlagEnum(ED, Val, false);
717 } else {
718 while (EI != EIEnd && EI->first < Val)
719 EI++;
720
721 if (EI != EIEnd && EI->first == Val)
722 return false;
723 }
724
Dmitri Gribenko58683752013-12-05 22:52:07 +0000725 return true;
726}
727
John McCalldadc5752010-08-24 06:29:42 +0000728StmtResult
John McCallb268a282010-08-23 23:25:46 +0000729Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
730 Stmt *BodyStmt) {
731 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000732 assert(SS == getCurFunction()->SwitchStack.back() &&
733 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000734
David Majnemer418ad3f2014-12-15 07:46:12 +0000735 getCurFunction()->SwitchStack.pop_back();
736
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000737 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000738 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000739
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000740 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000741 if (!CondExpr) return StmtError();
742
743 QualType CondType = CondExpr->getType();
744
John McCalld3dfbd62010-05-18 03:19:21 +0000745 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000746 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000747 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000748
Chris Lattnera96d4272009-10-16 16:45:22 +0000749 // C++ 6.4.2.p2:
750 // Integral promotions are performed (on the switch condition).
751 //
752 // A case value unrepresentable by the original switch condition
753 // type (before the promotion) doesn't make sense, even when it can
754 // be represented by the promoted type. Therefore we need to find
755 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000756 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000757 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000758 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000759 // appropriate type now, just return an error.
760 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000761 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000762
Chris Lattner4ebae652010-04-16 23:34:13 +0000763 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000764 // switch(bool_expr) {...} is often a programmer error, e.g.
765 // switch(n && mask) { ... } // Doh - should be "n & mask".
766 // One can always use an if statement instead of switch(bool_expr).
767 Diag(SwitchLoc, diag::warn_bool_switch_condition)
768 << CondExpr->getSourceRange();
769 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000770 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000771
Richard Smith077d0832014-08-04 00:40:48 +0000772 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000773 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000774 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000775 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000776 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
777 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
778
779 // Get the width and signedness that the condition might actually have, for
780 // warning purposes.
781 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
782 // type.
783 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000784 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000785 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000786 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000787
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000788 // Accumulate all of the case values in a vector so that we can sort them
789 // and detect duplicates. This vector contains the APInt for the case after
790 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000791 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000792 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000794 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000795 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
796 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000797
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattner10cb5e52007-08-23 06:23:56 +0000800 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000802 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000803 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000804
Anders Carlsson51873c22007-07-22 07:07:56 +0000805 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000806 if (TheDefaultStmt) {
807 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000808 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000809
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000810 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000811 // we'll return a valid AST. This requires recursing down the AST and
812 // finding it, not something we are set up to do right now. For now,
813 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000814 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000815 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000816 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000818 } else {
819 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattnera65e1f32008-01-16 19:17:22 +0000821 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000822
823 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
824 HasDependentValue = true;
825 break;
826 }
Mike Stump11289f42009-09-09 15:08:12 +0000827
Richard Smithf8379a02012-01-18 23:55:52 +0000828 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000829
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000830 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000831 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
832 // constant expression of the promoted type of the switch condition.
833 ExprResult ConvLo =
834 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
835 if (ConvLo.isInvalid()) {
836 CaseListIsErroneous = true;
837 continue;
838 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000839 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000840 } else {
841 // We already verified that the expression has a i-c-e value (C99
842 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000843 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000844
845 // If the LHS is not the same type as the condition, insert an implicit
846 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000847 Lo = DefaultLvalueConversion(Lo).get();
848 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000849 }
850
Richard Smith077d0832014-08-04 00:40:48 +0000851 // Check the unconverted value is within the range of possible values of
852 // the switch expression.
853 checkCaseValue(*this, Lo->getLocStart(), LoVal,
854 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
855
856 // Convert the value to the same width/sign as the condition.
857 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000858
Chris Lattnera65e1f32008-01-16 19:17:22 +0000859 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner10cb5e52007-08-23 06:23:56 +0000861 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000862 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000863 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000864 CS->getRHS()->isValueDependent()) {
865 HasDependentValue = true;
866 break;
867 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000868 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000869 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000870 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000871 }
872 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000873
874 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000875 // If we don't have a default statement, check whether the
876 // condition is constant.
877 llvm::APSInt ConstantCondValue;
878 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000879 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000880 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
881 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000882 assert(!HasConstantCond ||
883 (ConstantCondValue.getBitWidth() == CondWidth &&
884 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000885 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000886 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000887
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000888 // Sort all the scalar case values so we can easily detect duplicates.
889 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
890
891 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000892 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
893 if (ShouldCheckConstantCond &&
894 CaseVals[i].first == ConstantCondValue)
895 ShouldCheckConstantCond = false;
896
897 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000898 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000899 // First, determine if either case value has a name
900 StringRef PrevString, CurrString;
901 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
902 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
903 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
904 PrevString = DeclRef->getDecl()->getName();
905 }
906 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
907 CurrString = DeclRef->getDecl()->getName();
908 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000909 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000910 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000911
912 if (PrevString == CurrString)
913 Diag(CaseVals[i].second->getLHS()->getLocStart(),
914 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000915 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000916 else
917 Diag(CaseVals[i].second->getLHS()->getLocStart(),
918 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000919 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
920 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000921 CaseValStr;
922
John McCalld3dfbd62010-05-18 03:19:21 +0000923 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000924 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000925 // FIXME: We really want to remove the bogus case stmt from the
926 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000927 CaseListIsErroneous = true;
928 }
929 }
930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000932 // Detect duplicate case ranges, which usually don't exist at all in
933 // the first place.
934 if (!CaseRanges.empty()) {
935 // Sort all the case ranges by their low value so we can easily detect
936 // overlaps between ranges.
937 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000938
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000939 // Scan the ranges, computing the high values and removing empty ranges.
940 std::vector<llvm::APSInt> HiVals;
941 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000942 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000943 CaseStmt *CR = CaseRanges[i].second;
944 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000945 llvm::APSInt HiVal;
946
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000947 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000948 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
949 // constant expression of the promoted type of the switch condition.
950 ExprResult ConvHi =
951 CheckConvertedConstantExpression(Hi, CondType, HiVal,
952 CCEK_CaseValue);
953 if (ConvHi.isInvalid()) {
954 CaseListIsErroneous = true;
955 continue;
956 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000957 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000958 } else {
959 HiVal = Hi->EvaluateKnownConstInt(Context);
960
961 // If the RHS is not the same type as the condition, insert an
962 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000963 Hi = DefaultLvalueConversion(Hi).get();
964 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000965 }
Mike Stump11289f42009-09-09 15:08:12 +0000966
Richard Smith077d0832014-08-04 00:40:48 +0000967 // Check the unconverted value is within the range of possible values of
968 // the switch expression.
969 checkCaseValue(*this, Hi->getLocStart(), HiVal,
970 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
971
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000972 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000973 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000975 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000976
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000977 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000978 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
980 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000981 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000982 CaseRanges.erase(CaseRanges.begin()+i);
983 --i, --e;
984 continue;
985 }
John McCalld3dfbd62010-05-18 03:19:21 +0000986
987 if (ShouldCheckConstantCond &&
988 LoVal <= ConstantCondValue &&
989 ConstantCondValue <= HiVal)
990 ShouldCheckConstantCond = false;
991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 HiVals.push_back(HiVal);
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000995 // Rescan the ranges, looking for overlap with singleton values and other
996 // ranges. Since the range list is sorted, we only need to compare case
997 // ranges with their neighbors.
998 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
999 llvm::APSInt &CRLo = CaseRanges[i].first;
1000 llvm::APSInt &CRHi = HiVals[i];
1001 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 // Check to see whether the case range overlaps with any
1004 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001005 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001006 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001007
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001008 // Find the smallest value >= the lower bound. If I is in the
1009 // case range, then we have overlap.
1010 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1011 CaseVals.end(), CRLo,
1012 CaseCompareFunctor());
1013 if (I != CaseVals.end() && I->first < CRHi) {
1014 OverlapVal = I->first; // Found overlap with scalar.
1015 OverlapStmt = I->second;
1016 }
Mike Stump11289f42009-09-09 15:08:12 +00001017
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001018 // Find the smallest value bigger than the upper bound.
1019 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1020 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1021 OverlapVal = (I-1)->first; // Found overlap with scalar.
1022 OverlapStmt = (I-1)->second;
1023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001025 // Check to see if this case stmt overlaps with the subsequent
1026 // case range.
1027 if (i && CRLo <= HiVals[i-1]) {
1028 OverlapVal = HiVals[i-1]; // Found overlap with range.
1029 OverlapStmt = CaseRanges[i-1].second;
1030 }
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001032 if (OverlapStmt) {
1033 // If we have a duplicate, report it.
1034 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1035 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001036 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001038 // FIXME: We really want to remove the bogus case stmt from the
1039 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001040 CaseListIsErroneous = true;
1041 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001042 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001043 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001044
John McCalld3dfbd62010-05-18 03:19:21 +00001045 // Complain if we have a constant condition and we didn't find a match.
1046 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1047 // TODO: it would be nice if we printed enums as enums, chars as
1048 // chars, etc.
1049 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1050 << ConstantCondValue.toString(10)
1051 << CondExpr->getSourceRange();
1052 }
1053
1054 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001055 // values. We only issue a warning if there is not 'default:', but
1056 // we still do the analysis to preserve this information in the AST
1057 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001058 //
Chris Lattner51679082010-09-16 17:09:42 +00001059 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001060
Douglas Gregorbd6839732010-02-08 22:24:16 +00001061 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001062 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001063 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001064 EnumValsTy EnumVals;
1065
John McCalld3dfbd62010-05-18 03:19:21 +00001066 // Gather all enum values, set their type and sort them,
1067 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001068 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001069 llvm::APSInt Val = EDI->getInitVal();
1070 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001071 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001072 }
1073 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001074 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001075 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001076
1077 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001078 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001079 CI != CaseVals.end(); CI++) {
1080 Expr *CaseExpr = CI->second->getLHS();
1081 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1082 CI->first))
1083 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1084 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001085 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001086
David Blaikiee476f972012-01-22 02:31:55 +00001087 // See which of case ranges aren't in enum
1088 EI = EnumVals.begin();
1089 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001090 RI != CaseRanges.end(); RI++) {
1091 Expr *CaseExpr = RI->second->getLHS();
1092 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1093 RI->first))
1094 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1095 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001096
Chad Rosier02a84392012-08-10 17:56:09 +00001097 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001098 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1099 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001100
1101 CaseExpr = RI->second->getRHS();
1102 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1103 Hi))
1104 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1105 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Ted Kremenekc42f3452010-09-09 00:05:53 +00001108 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001109 auto CI = CaseVals.begin();
1110 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001111 bool hasCasesNotInSwitch = false;
1112
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001113 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001114
Alexis Hunt724f14e2014-11-28 00:53:20 +00001115 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001116 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001117 while (CI != CaseVals.end() && CI->first < EI->first)
1118 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001119
Douglas Gregorbd6839732010-02-08 22:24:16 +00001120 if (CI != CaseVals.end() && CI->first == EI->first)
1121 continue;
1122
Ted Kremenekc42f3452010-09-09 00:05:53 +00001123 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001124 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001125 llvm::APSInt Hi =
1126 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001127 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001128 if (EI->first <= Hi)
1129 break;
1130 }
1131
Ted Kremenekc42f3452010-09-09 00:05:53 +00001132 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001133 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001134 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001135 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137
David Blaikie60ac6382012-01-23 04:46:12 +00001138 if (TheDefaultStmt && UnhandledNames.empty())
1139 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001140
Chris Lattner51679082010-09-16 17:09:42 +00001141 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001142 if (!UnhandledNames.empty()) {
1143 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1144 TheDefaultStmt ? diag::warn_def_missing_case
1145 : diag::warn_missing_case)
1146 << (int)UnhandledNames.size();
1147
1148 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1149 I != E; ++I)
1150 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001151 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001152
1153 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001154 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001155 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001156 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001157
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001158 if (BodyStmt)
1159 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1160 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001161
Mike Stump87c57ac2009-05-16 07:39:55 +00001162 // FIXME: If the case list was broken is some way, we don't have a good system
1163 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001164 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001165 return StmtError();
1166
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001167 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001168}
1169
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001170void
1171Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1172 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001173 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001174 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001175
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001176 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001177 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001178 SrcType->isIntegerType()) {
1179 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1180 SrcExpr->isIntegerConstantExpr(Context)) {
1181 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001182 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001183 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1184
1185 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001186 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001187 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001188
Alexis Hunt724f14e2014-11-28 00:53:20 +00001189 if (ED->hasAttr<FlagEnumAttr>()) {
1190 if (!IsValueInFlagEnum(ED, RhsVal, true))
1191 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001192 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001193 } else {
1194 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1195 EnumValsTy;
1196 EnumValsTy EnumVals;
1197
1198 // Gather all enum values, set their type and sort them,
1199 // allowing easier comparison with rhs constant.
1200 for (auto *EDI : ED->enumerators()) {
1201 llvm::APSInt Val = EDI->getInitVal();
1202 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1203 EnumVals.push_back(std::make_pair(Val, EDI));
1204 }
1205 if (EnumVals.empty())
1206 return;
1207 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1208 EnumValsTy::iterator EIend =
1209 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1210
1211 // See which values aren't in the enum.
1212 EnumValsTy::const_iterator EI = EnumVals.begin();
1213 while (EI != EIend && EI->first < RhsVal)
1214 EI++;
1215 if (EI == EIend || EI->first != RhsVal) {
1216 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1217 << DstType.getUnqualifiedType();
1218 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001219 }
1220 }
1221 }
1222}
1223
John McCalldadc5752010-08-24 06:29:42 +00001224StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001226 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001227 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228
Craig Topperc3ec1492014-05-26 06:22:03 +00001229 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001230 if (CondVar) {
1231 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001232 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001233 CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001234 if (CondResult.isInvalid())
1235 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001236 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001237 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001238 if (!ConditionExpr)
1239 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001240 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
John McCallb268a282010-08-23 23:25:46 +00001242 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001244 if (isa<NullStmt>(Body))
1245 getCurCompoundScope().setHasEmptyLoopBodies();
1246
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001247 return new (Context)
1248 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001249}
1250
John McCalldadc5752010-08-24 06:29:42 +00001251StmtResult
John McCallb268a282010-08-23 23:25:46 +00001252Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001253 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001254 Expr *Cond, SourceLocation CondRParen) {
1255 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001256
Serge Pavlov09f99242014-01-23 15:05:00 +00001257 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001258 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001259 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001260 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001261 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001262
Richard Smith945f8d32013-01-14 22:39:08 +00001263 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001264 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001265 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001266 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001267
John McCallb268a282010-08-23 23:25:46 +00001268 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001269
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001270 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001271}
1272
Richard Trieu451a5db2012-04-30 18:01:30 +00001273namespace {
1274 // This visitor will traverse a conditional statement and store all
1275 // the evaluated decls into a vector. Simple is set to true if none
1276 // of the excluded constructs are used.
1277 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001278 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001279 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001280 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001281 public:
1282 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001283
Craig Topper4dd9b432014-08-17 23:49:53 +00001284 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001285 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001286 Inherited(S.Context),
1287 Decls(Decls),
1288 Ranges(Ranges),
1289 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001290
Richard Trieu9d228802013-05-31 22:46:45 +00001291 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001292
Richard Trieu9d228802013-05-31 22:46:45 +00001293 // Replaces the method in EvaluatedExprVisitor.
1294 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001295 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001296 }
1297
1298 // Any Stmt not whitelisted will cause the condition to be marked complex.
1299 void VisitStmt(Stmt *S) {
1300 Simple = false;
1301 }
1302
1303 void VisitBinaryOperator(BinaryOperator *E) {
1304 Visit(E->getLHS());
1305 Visit(E->getRHS());
1306 }
1307
1308 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001309 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001310 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001311
Richard Trieu9d228802013-05-31 22:46:45 +00001312 void VisitUnaryOperator(UnaryOperator *E) {
1313 // Skip checking conditionals with derefernces.
1314 if (E->getOpcode() == UO_Deref)
1315 Simple = false;
1316 else
1317 Visit(E->getSubExpr());
1318 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001319
Richard Trieu9d228802013-05-31 22:46:45 +00001320 void VisitConditionalOperator(ConditionalOperator *E) {
1321 Visit(E->getCond());
1322 Visit(E->getTrueExpr());
1323 Visit(E->getFalseExpr());
1324 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001325
Richard Trieu9d228802013-05-31 22:46:45 +00001326 void VisitParenExpr(ParenExpr *E) {
1327 Visit(E->getSubExpr());
1328 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001329
Richard Trieu9d228802013-05-31 22:46:45 +00001330 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1331 Visit(E->getOpaqueValue()->getSourceExpr());
1332 Visit(E->getFalseExpr());
1333 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001334
Richard Trieu9d228802013-05-31 22:46:45 +00001335 void VisitIntegerLiteral(IntegerLiteral *E) { }
1336 void VisitFloatingLiteral(FloatingLiteral *E) { }
1337 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1338 void VisitCharacterLiteral(CharacterLiteral *E) { }
1339 void VisitGNUNullExpr(GNUNullExpr *E) { }
1340 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001341
Richard Trieu9d228802013-05-31 22:46:45 +00001342 void VisitDeclRefExpr(DeclRefExpr *E) {
1343 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1344 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001345
Richard Trieu9d228802013-05-31 22:46:45 +00001346 Ranges.push_back(E->getSourceRange());
1347
1348 Decls.insert(VD);
1349 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001350
1351 }; // end class DeclExtractor
1352
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001353 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001354 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001355 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001356 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001357 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
Richard Trieu9d228802013-05-31 22:46:45 +00001359 public:
1360 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001361
Craig Topper4dd9b432014-08-17 23:49:53 +00001362 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001363 Stmt *Statement) :
1364 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1365 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001368 }
1369
Richard Trieu9d228802013-05-31 22:46:45 +00001370 void VisitReturnStmt(ReturnStmt *S) {
1371 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001372 }
1373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 void VisitBreakStmt(BreakStmt *S) {
1375 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001376 }
1377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitGotoStmt(GotoStmt *S) {
1379 FoundDecl = true;
1380 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001381
Richard Trieu9d228802013-05-31 22:46:45 +00001382 void VisitCastExpr(CastExpr *E) {
1383 if (E->getCastKind() == CK_LValueToRValue)
1384 CheckLValueToRValueCast(E->getSubExpr());
1385 else
1386 Visit(E->getSubExpr());
1387 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001388
Richard Trieu9d228802013-05-31 22:46:45 +00001389 void CheckLValueToRValueCast(Expr *E) {
1390 E = E->IgnoreParenImpCasts();
1391
1392 if (isa<DeclRefExpr>(E)) {
1393 return;
1394 }
1395
1396 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1397 Visit(CO->getCond());
1398 CheckLValueToRValueCast(CO->getTrueExpr());
1399 CheckLValueToRValueCast(CO->getFalseExpr());
1400 return;
1401 }
1402
1403 if (BinaryConditionalOperator *BCO =
1404 dyn_cast<BinaryConditionalOperator>(E)) {
1405 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1406 CheckLValueToRValueCast(BCO->getFalseExpr());
1407 return;
1408 }
1409
1410 Visit(E);
1411 }
1412
1413 void VisitDeclRefExpr(DeclRefExpr *E) {
1414 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1415 if (Decls.count(VD))
1416 FoundDecl = true;
1417 }
1418
1419 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001420
1421 }; // end class DeclMatcher
1422
1423 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1424 Expr *Third, Stmt *Body) {
1425 // Condition is empty
1426 if (!Second) return;
1427
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001428 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1429 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001430 return;
1431
1432 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1433 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001434 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001435 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001436 DE.Visit(Second);
1437
1438 // Don't analyze complex conditionals.
1439 if (!DE.isSimple()) return;
1440
1441 // No decls found.
1442 if (Decls.size() == 0) return;
1443
Richard Trieu0030f1d2012-05-04 03:01:54 +00001444 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001445 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1446 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001447 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001448 if ((*I)->getType().isVolatileQualified() ||
1449 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001450
1451 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1452 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1453 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1454 return;
1455
1456 // Load decl names into diagnostic.
1457 if (Decls.size() > 4)
1458 PDiag << 0;
1459 else {
1460 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001461 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1462 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001463 I != E; ++I)
1464 PDiag << (*I)->getDeclName();
1465 }
1466
1467 // Load SourceRanges into diagnostic if there is room.
1468 // Otherwise, load the SourceRange of the conditional expression.
1469 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001470 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001471 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001472 I != E; ++I)
1473 PDiag << *I;
1474 else
1475 PDiag << Second->getSourceRange();
1476
1477 S.Diag(Ranges.begin()->getBegin(), PDiag);
1478 }
1479
Richard Trieu4e7c9622013-08-06 21:31:54 +00001480 // If Statement is an incemement or decrement, return true and sets the
1481 // variables Increment and DRE.
1482 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1483 DeclRefExpr *&DRE) {
1484 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1485 switch (UO->getOpcode()) {
1486 default: return false;
1487 case UO_PostInc:
1488 case UO_PreInc:
1489 Increment = true;
1490 break;
1491 case UO_PostDec:
1492 case UO_PreDec:
1493 Increment = false;
1494 break;
1495 }
1496 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1497 return DRE;
1498 }
1499
1500 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1501 FunctionDecl *FD = Call->getDirectCallee();
1502 if (!FD || !FD->isOverloadedOperator()) return false;
1503 switch (FD->getOverloadedOperator()) {
1504 default: return false;
1505 case OO_PlusPlus:
1506 Increment = true;
1507 break;
1508 case OO_MinusMinus:
1509 Increment = false;
1510 break;
1511 }
1512 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1513 return DRE;
1514 }
1515
1516 return false;
1517 }
1518
Serge Pavlov09f99242014-01-23 15:05:00 +00001519 // A visitor to determine if a continue or break statement is a
1520 // subexpression.
1521 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1522 SourceLocation BreakLoc;
1523 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001524 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001525 BreakContinueFinder(Sema &S, Stmt* Body) :
1526 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001527 Visit(Body);
1528 }
1529
Serge Pavlov09f99242014-01-23 15:05:00 +00001530 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001531
1532 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001533 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001534 }
1535
Serge Pavlov09f99242014-01-23 15:05:00 +00001536 void VisitBreakStmt(BreakStmt* E) {
1537 BreakLoc = E->getBreakLoc();
1538 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001539
Serge Pavlov09f99242014-01-23 15:05:00 +00001540 bool ContinueFound() { return ContinueLoc.isValid(); }
1541 bool BreakFound() { return BreakLoc.isValid(); }
1542 SourceLocation GetContinueLoc() { return ContinueLoc; }
1543 SourceLocation GetBreakLoc() { return BreakLoc; }
1544
1545 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001546
1547 // Emit a warning when a loop increment/decrement appears twice per loop
1548 // iteration. The conditions which trigger this warning are:
1549 // 1) The last statement in the loop body and the third expression in the
1550 // for loop are both increment or both decrement of the same variable
1551 // 2) No continue statements in the loop body.
1552 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1553 // Return when there is nothing to check.
1554 if (!Body || !Third) return;
1555
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001556 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1557 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001558 return;
1559
1560 // Get the last statement from the loop body.
1561 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1562 if (!CS || CS->body_empty()) return;
1563 Stmt *LastStmt = CS->body_back();
1564 if (!LastStmt) return;
1565
1566 bool LoopIncrement, LastIncrement;
1567 DeclRefExpr *LoopDRE, *LastDRE;
1568
1569 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1570 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1571
1572 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001573 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001574 if (LoopIncrement != LastIncrement ||
1575 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1576
Serge Pavlov09f99242014-01-23 15:05:00 +00001577 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001578
1579 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1580 << LastDRE->getDecl() << LastIncrement;
1581 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1582 << LoopIncrement;
1583 }
1584
Richard Trieu451a5db2012-04-30 18:01:30 +00001585} // end namespace
1586
Serge Pavlov09f99242014-01-23 15:05:00 +00001587
1588void Sema::CheckBreakContinueBinding(Expr *E) {
1589 if (!E || getLangOpts().CPlusPlus)
1590 return;
1591 BreakContinueFinder BCFinder(*this, E);
1592 Scope *BreakParent = CurScope->getBreakParent();
1593 if (BCFinder.BreakFound() && BreakParent) {
1594 if (BreakParent->getFlags() & Scope::SwitchScope) {
1595 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1596 } else {
1597 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1598 << "break";
1599 }
1600 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1601 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1602 << "continue";
1603 }
1604}
1605
John McCalldadc5752010-08-24 06:29:42 +00001606StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001607Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001608 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001609 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001610 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001611 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001612 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001613 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1614 // declare identifiers for objects having storage class 'auto' or
1615 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001616 for (auto *DI : DS->decls()) {
1617 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001618 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001619 VD = nullptr;
1620 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001621 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1622 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001623 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001624 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001625 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001626 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001627
Serge Pavlov09f99242014-01-23 15:05:00 +00001628 CheckBreakContinueBinding(second.get());
1629 CheckBreakContinueBinding(third.get());
1630
Richard Trieu451a5db2012-04-30 18:01:30 +00001631 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001632 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001633
John McCalldadc5752010-08-24 06:29:42 +00001634 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001635 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001636 if (secondVar) {
1637 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001638 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001639 SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001640 if (SecondResult.isInvalid())
1641 return StmtError();
1642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001644 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001645
Anders Carlsson1682af52009-08-01 01:39:59 +00001646 DiagnoseUnusedExprResult(First);
1647 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001648 DiagnoseUnusedExprResult(Body);
1649
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001650 if (isa<NullStmt>(Body))
1651 getCurCompoundScope().setHasEmptyLoopBodies();
1652
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001653 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1654 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001655}
1656
John McCall34376a62010-12-04 03:47:34 +00001657/// In an Objective C collection iteration statement:
1658/// for (x in y)
1659/// x can be an arbitrary l-value expression. Bind it up as a
1660/// full-expression.
1661StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001662 // Reduce placeholder expressions here. Note that this rejects the
1663 // use of pseudo-object l-values in this position.
1664 ExprResult result = CheckPlaceholderExpr(E);
1665 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001666 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001667
Richard Smith945f8d32013-01-14 22:39:08 +00001668 ExprResult FullExpr = ActOnFinishFullExpr(E);
1669 if (FullExpr.isInvalid())
1670 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001671 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001672}
1673
John McCall53848232011-07-27 01:07:15 +00001674ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001675Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1676 if (!collection)
1677 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001678
Kaelyn Takata15867822014-11-21 18:48:04 +00001679 ExprResult result = CorrectDelayedTyposInExpr(collection);
1680 if (!result.isUsable())
1681 return ExprError();
1682 collection = result.get();
1683
John McCall53848232011-07-27 01:07:15 +00001684 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001685 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001686
1687 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001688 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001689 if (result.isInvalid())
1690 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001691 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001692
1693 // The operand needs to have object-pointer type.
1694 // TODO: should we do a contextual conversion?
1695 const ObjCObjectPointerType *pointerType =
1696 collection->getType()->getAs<ObjCObjectPointerType>();
1697 if (!pointerType)
1698 return Diag(forLoc, diag::err_collection_expr_type)
1699 << collection->getType() << collection->getSourceRange();
1700
1701 // Check that the operand provides
1702 // - countByEnumeratingWithState:objects:count:
1703 const ObjCObjectType *objectType = pointerType->getObjectType();
1704 ObjCInterfaceDecl *iface = objectType->getInterface();
1705
1706 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001707 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001708 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001709 (getLangOpts().ObjCAutoRefCount
1710 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1711 diag::err_arc_collection_forward, collection)
1712 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001713 // Otherwise, if we have any useful type information, check that
1714 // the type declares the appropriate method.
1715 } else if (iface || !objectType->qual_empty()) {
1716 IdentifierInfo *selectorIdents[] = {
1717 &Context.Idents.get("countByEnumeratingWithState"),
1718 &Context.Idents.get("objects"),
1719 &Context.Idents.get("count")
1720 };
1721 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1722
Craig Topperc3ec1492014-05-26 06:22:03 +00001723 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001724
1725 // If there's an interface, look in both the public and private APIs.
1726 if (iface) {
1727 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001728 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001729 }
1730
1731 // Also check protocol qualifiers.
1732 if (!method)
1733 method = LookupMethodInQualifiedType(selector, pointerType,
1734 /*instance*/ true);
1735
1736 // If we didn't find it anywhere, give up.
1737 if (!method) {
1738 Diag(forLoc, diag::warn_collection_expr_type)
1739 << collection->getType() << selector << collection->getSourceRange();
1740 }
1741
1742 // TODO: check for an incompatible signature?
1743 }
1744
1745 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001746 return collection;
John McCall53848232011-07-27 01:07:15 +00001747}
1748
John McCalldadc5752010-08-24 06:29:42 +00001749StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001750Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001751 Stmt *First, Expr *collection,
1752 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001753
1754 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001755 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001756
Fariborz Jahanian93977672008-01-10 20:33:58 +00001757 if (First) {
1758 QualType FirstType;
1759 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001760 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001761 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1762 diag::err_toomany_element_decls));
1763
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001764 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1765 if (!D || D->isInvalidDecl())
1766 return StmtError();
1767
John McCall31168b02011-06-15 23:02:42 +00001768 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001769 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1770 // declare identifiers for objects having storage class 'auto' or
1771 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001772 if (!D->hasLocalStorage())
1773 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001774 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001775
1776 // If the type contained 'auto', deduce the 'auto' to 'id'.
1777 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001778 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1779 VK_RValue);
1780 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001781 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1782 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001783 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001784 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001785 D->setInvalidDecl();
1786 return StmtError();
1787 }
1788
Richard Smith061f1e22013-04-30 21:23:01 +00001789 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001790
1791 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001792 SourceLocation Loc =
1793 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001794 Diag(Loc, diag::warn_auto_var_is_id)
1795 << D->getDeclName();
1796 }
1797 }
1798
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001799 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001800 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001801 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001802 return StmtError(Diag(First->getLocStart(),
1803 diag::err_selector_element_not_lvalue)
1804 << First->getSourceRange());
1805
Mike Stump11289f42009-09-09 15:08:12 +00001806 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001807 if (FirstType.isConstQualified())
1808 Diag(ForLoc, diag::err_selector_element_const_type)
1809 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001810 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001811 if (!FirstType->isDependentType() &&
1812 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001813 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001814 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1815 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001816 }
Chad Rosier02a84392012-08-10 17:56:09 +00001817
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001818 if (CollectionExprResult.isInvalid())
1819 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001820
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001821 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001822 if (CollectionExprResult.isInvalid())
1823 return StmtError();
1824
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001825 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1826 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001827}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001828
Richard Smith02e85f32011-04-14 22:09:26 +00001829/// Finish building a variable declaration for a for-range statement.
1830/// \return true if an error occurs.
1831static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001832 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001833 if (Decl->getType()->isUndeducedType()) {
1834 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1835 if (!Res.isUsable()) {
1836 Decl->setInvalidDecl();
1837 return true;
1838 }
1839 Init = Res.get();
1840 }
1841
Richard Smith02e85f32011-04-14 22:09:26 +00001842 // Deduce the type for the iterator variable now rather than leaving it to
1843 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001844 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001845 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001846 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001847 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001848 SemaRef.Diag(Loc, DiagID) << Init->getType();
1849 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001850 Decl->setInvalidDecl();
1851 return true;
1852 }
Richard Smith061f1e22013-04-30 21:23:01 +00001853 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001854
John McCall31168b02011-06-15 23:02:42 +00001855 // In ARC, infer lifetime.
1856 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1857 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001858 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001859 SemaRef.inferObjCARCLifetime(Decl))
1860 Decl->setInvalidDecl();
1861
Richard Smith02e85f32011-04-14 22:09:26 +00001862 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1863 /*TypeMayContainAuto=*/false);
1864 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001865 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001866 return false;
1867}
1868
Sam Panzer0f384432012-08-21 00:52:01 +00001869namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001870// An enum to represent whether something is dealing with a call to begin()
1871// or a call to end() in a range-based for loop.
1872enum BeginEndFunction {
1873 BEF_begin,
1874 BEF_end
1875};
Sam Panzer0f384432012-08-21 00:52:01 +00001876
Richard Smith02e85f32011-04-14 22:09:26 +00001877/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001878/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001879/// nor from the diagnostics produced when analysing the implicit expressions
1880/// required in a for-range statement.
1881void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001882 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001883 CallExpr *CE = dyn_cast<CallExpr>(E);
1884 if (!CE)
1885 return;
1886 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1887 if (!D)
1888 return;
1889 SourceLocation Loc = D->getLocation();
1890
1891 std::string Description;
1892 bool IsTemplate = false;
1893 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1894 Description = SemaRef.getTemplateArgumentBindingsText(
1895 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1896 IsTemplate = true;
1897 }
1898
1899 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1900 << BEF << IsTemplate << Description << E->getType();
1901}
1902
Sam Panzer0f384432012-08-21 00:52:01 +00001903/// Build a variable declaration for a for-range statement.
1904VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1905 QualType Type, const char *Name) {
1906 DeclContext *DC = SemaRef.CurContext;
1907 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1908 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1909 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001910 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001911 Decl->setImplicit();
1912 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001913}
1914
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001915}
Richard Smith02e85f32011-04-14 22:09:26 +00001916
Fariborz Jahanian00213472012-07-06 19:04:04 +00001917static bool ObjCEnumerationCollection(Expr *Collection) {
1918 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001919 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001920}
1921
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001922/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001923///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001924/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001925/// A range-based for statement is equivalent to
1926///
1927/// {
1928/// auto && __range = range-init;
1929/// for ( auto __begin = begin-expr,
1930/// __end = end-expr;
1931/// __begin != __end;
1932/// ++__begin ) {
1933/// for-range-declaration = *__begin;
1934/// statement
1935/// }
1936/// }
1937///
1938/// The body of the loop is not available yet, since it cannot be analysed until
1939/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00001940StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1941 SourceLocation CoawaitLoc, Stmt *First,
1942 SourceLocation ColonLoc, Expr *Range,
1943 SourceLocation RParenLoc,
1944 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001945 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001946 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001947
Richard Smith3249fed2013-08-21 01:40:36 +00001948 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001949 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001950
1951 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1952 assert(DS && "first part of for range not a decl stmt");
1953
1954 if (!DS->isSingleDecl()) {
1955 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1956 return StmtError();
1957 }
Richard Smith02e85f32011-04-14 22:09:26 +00001958
Richard Smith3249fed2013-08-21 01:40:36 +00001959 Decl *LoopVar = DS->getSingleDecl();
1960 if (LoopVar->isInvalidDecl() || !Range ||
1961 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1962 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001963 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001964 }
Richard Smith02e85f32011-04-14 22:09:26 +00001965
Richard Smithcfd53b42015-10-22 06:13:50 +00001966 // Coroutines: 'for co_await' implicitly co_awaits its range.
1967 if (CoawaitLoc.isValid()) {
Richard Smith9f690bd2015-10-27 06:02:45 +00001968 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
Richard Smithcfd53b42015-10-22 06:13:50 +00001969 if (Coawait.isInvalid()) return StmtError();
1970 Range = Coawait.get();
1971 }
1972
Richard Smith02e85f32011-04-14 22:09:26 +00001973 // Build auto && __range = range-init
1974 SourceLocation RangeLoc = Range->getLocStart();
1975 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1976 Context.getAutoRRefDeductType(),
1977 "__range");
1978 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001979 diag::err_for_range_deduction_failure)) {
1980 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001981 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001982 }
Richard Smith02e85f32011-04-14 22:09:26 +00001983
1984 // Claim the type doesn't contain auto: we've already done the checking.
1985 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001986 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001987 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001988 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001989 if (RangeDecl.isInvalid()) {
1990 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001991 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001992 }
Richard Smith02e85f32011-04-14 22:09:26 +00001993
Richard Smithcfd53b42015-10-22 06:13:50 +00001994 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001995 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1996 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001997}
1998
1999/// \brief Create the initialization, compare, and increment steps for
2000/// the range-based for loop expression.
2001/// This function does not handle array-based for loops,
2002/// which are created in Sema::BuildCXXForRangeStmt.
2003///
2004/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2005/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2006/// CandidateSet and BEF are set and some non-success value is returned on
2007/// failure.
Richard Smith9f690bd2015-10-27 06:02:45 +00002008static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
Sam Panzer0f384432012-08-21 00:52:01 +00002009 Expr *BeginRange, Expr *EndRange,
2010 QualType RangeType,
2011 VarDecl *BeginVar,
2012 VarDecl *EndVar,
2013 SourceLocation ColonLoc,
2014 OverloadCandidateSet *CandidateSet,
2015 ExprResult *BeginExpr,
2016 ExprResult *EndExpr,
Richard Smith9f690bd2015-10-27 06:02:45 +00002017 BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002018 DeclarationNameInfo BeginNameInfo(
2019 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2020 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2021 ColonLoc);
2022
2023 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2024 Sema::LookupMemberName);
2025 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2026
2027 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2028 // - if _RangeT is a class type, the unqualified-ids begin and end are
2029 // looked up in the scope of class _RangeT as if by class member access
2030 // lookup (3.4.5), and if either (or both) finds at least one
2031 // declaration, begin-expr and end-expr are __range.begin() and
2032 // __range.end(), respectively;
2033 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2034 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2035
2036 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2037 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002038 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002039
2040 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2041 << RangeLoc << BeginRange->getType() << *BEF;
2042 return Sema::FRS_DiagnosticIssued;
2043 }
2044 } else {
2045 // - otherwise, begin-expr and end-expr are begin(__range) and
2046 // end(__range), respectively, where begin and end are looked up with
2047 // argument-dependent lookup (3.4.2). For the purposes of this name
2048 // lookup, namespace std is an associated namespace.
2049
2050 }
2051
Richard Smith9f690bd2015-10-27 06:02:45 +00002052 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002053 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002054 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002055 BeginMemberLookup, CandidateSet,
2056 BeginRange, BeginExpr);
2057
Richard Smith9f690bd2015-10-27 06:02:45 +00002058 if (RangeStatus != Sema::FRS_Success) {
2059 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2060 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2061 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002062 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002063 }
Sam Panzer0f384432012-08-21 00:52:01 +00002064 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2065 diag::err_for_range_iter_deduction_failure)) {
2066 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2067 return Sema::FRS_DiagnosticIssued;
2068 }
2069
Richard Smith9f690bd2015-10-27 06:02:45 +00002070 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002071 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002072 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002073 EndMemberLookup, CandidateSet,
2074 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002075 if (RangeStatus != Sema::FRS_Success) {
2076 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2077 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2078 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002079 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002080 }
Sam Panzer0f384432012-08-21 00:52:01 +00002081 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2082 diag::err_for_range_iter_deduction_failure)) {
2083 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2084 return Sema::FRS_DiagnosticIssued;
2085 }
2086 return Sema::FRS_Success;
2087}
2088
2089/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002090/// If the attempt fails, this function will return a valid, null StmtResult
2091/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002092static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2093 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002094 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002095 Stmt *LoopVarDecl,
2096 SourceLocation ColonLoc,
2097 Expr *Range,
2098 SourceLocation RangeLoc,
2099 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002100 // Determine whether we can rebuild the for-range statement with a
2101 // dereferenced range expression.
2102 ExprResult AdjustedRange;
2103 {
2104 Sema::SFINAETrap Trap(SemaRef);
2105
2106 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2107 if (AdjustedRange.isInvalid())
2108 return StmtResult();
2109
Richard Smith9f690bd2015-10-27 06:02:45 +00002110 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2111 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2112 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002113 if (SR.isInvalid())
2114 return StmtResult();
2115 }
2116
2117 // The attempt to dereference worked well enough that it could produce a valid
2118 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2119 // case there are any other (non-fatal) problems with it.
2120 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2121 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002122 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2123 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002124 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002125}
2126
Richard Smith3249fed2013-08-21 01:40:36 +00002127namespace {
2128/// RAII object to automatically invalidate a declaration if an error occurs.
2129struct InvalidateOnErrorScope {
2130 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2131 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2132 ~InvalidateOnErrorScope() {
2133 if (Enabled && Trap.hasErrorOccurred())
2134 D->setInvalidDecl();
2135 }
2136
2137 DiagnosticErrorTrap Trap;
2138 Decl *D;
2139 bool Enabled;
2140};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002141}
Richard Smith3249fed2013-08-21 01:40:36 +00002142
Richard Smitha05b3b52012-09-20 21:52:32 +00002143/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002144StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002145Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2146 SourceLocation ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002147 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2148 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002149 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002150 // FIXME: This should not be used during template instantiation. We should
2151 // pick up the set of unqualified lookup results for the != and + operators
2152 // in the initial parse.
2153 //
2154 // Testcase (accepts-invalid):
2155 // template<typename T> void f() { for (auto x : T()) {} }
2156 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2157 // bool operator!=(N::X, N::X); void operator++(N::X);
2158 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002159 Scope *S = getCurScope();
2160
2161 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2162 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2163 QualType RangeVarType = RangeVar->getType();
2164
2165 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2166 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2167
Richard Smith3249fed2013-08-21 01:40:36 +00002168 // If we hit any errors, mark the loop variable as invalid if its type
2169 // contains 'auto'.
2170 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2171 LoopVar->getType()->isUndeducedType());
2172
Richard Smith02e85f32011-04-14 22:09:26 +00002173 StmtResult BeginEndDecl = BeginEnd;
2174 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2175
Richard Smith27d807c2013-04-30 13:56:41 +00002176 if (RangeVarType->isDependentType()) {
2177 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002178 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002179
2180 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2181 // them in properly when we instantiate the loop.
2182 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2183 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2184 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002185 SourceLocation RangeLoc = RangeVar->getLocation();
2186
Ted Kremenekbed648e2011-10-10 22:36:28 +00002187 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2188
2189 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2190 VK_LValue, ColonLoc);
2191 if (BeginRangeRef.isInvalid())
2192 return StmtError();
2193
2194 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2195 VK_LValue, ColonLoc);
2196 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002197 return StmtError();
2198
2199 QualType AutoType = Context.getAutoDeductType();
2200 Expr *Range = RangeVar->getInit();
2201 if (!Range)
2202 return StmtError();
2203 QualType RangeType = Range->getType();
2204
2205 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002206 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002207 return StmtError();
2208
2209 // Build auto __begin = begin-expr, __end = end-expr.
2210 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2211 "__begin");
2212 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2213 "__end");
2214
2215 // Build begin-expr and end-expr and attach to __begin and __end variables.
2216 ExprResult BeginExpr, EndExpr;
2217 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2218 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2219 // __range + __bound, respectively, where __bound is the array bound. If
2220 // _RangeT is an array of unknown size or an array of incomplete type,
2221 // the program is ill-formed;
2222
2223 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002224 BeginExpr = BeginRangeRef;
2225 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002226 diag::err_for_range_iter_deduction_failure)) {
2227 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2228 return StmtError();
2229 }
2230
2231 // Find the array bound.
2232 ExprResult BoundExpr;
2233 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002234 BoundExpr = IntegerLiteral::Create(
2235 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002236 else if (const VariableArrayType *VAT =
2237 dyn_cast<VariableArrayType>(UnqAT))
2238 BoundExpr = VAT->getSizeExpr();
2239 else {
2240 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2241 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002242 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002243 }
2244
2245 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002246 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002247 BoundExpr.get());
2248 if (EndExpr.isInvalid())
2249 return StmtError();
2250 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2251 diag::err_for_range_iter_deduction_failure)) {
2252 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2253 return StmtError();
2254 }
2255 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002256 OverloadCandidateSet CandidateSet(RangeLoc,
2257 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002258 BeginEndFunction BEFFailure;
Sam Panzer0f384432012-08-21 00:52:01 +00002259 ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002260 BuildNonArrayForRange(*this, BeginRangeRef.get(),
Sam Panzer0f384432012-08-21 00:52:01 +00002261 EndRangeRef.get(), RangeType,
2262 BeginVar, EndVar, ColonLoc, &CandidateSet,
2263 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002264
Richard Smitha05b3b52012-09-20 21:52:32 +00002265 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002266 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002267 // If the range is being built from an array parameter, emit a
2268 // a diagnostic that it is being treated as a pointer.
2269 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2270 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2271 QualType ArrayTy = PVD->getOriginalType();
2272 QualType PointerTy = PVD->getType();
2273 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2274 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2275 << RangeLoc << PVD << ArrayTy << PointerTy;
2276 Diag(PVD->getLocation(), diag::note_declared_at);
2277 return StmtError();
2278 }
2279 }
2280 }
2281
2282 // If building the range failed, try dereferencing the range expression
2283 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002284 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002285 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002286 LoopVarDecl, ColonLoc,
2287 Range, RangeLoc,
2288 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002289 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002290 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002291 }
2292
Sam Panzer0f384432012-08-21 00:52:01 +00002293 // Otherwise, emit diagnostics if we haven't already.
2294 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002295 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002296 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2297 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002299 }
2300 // Return an error if no fix was discovered.
2301 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002302 return StmtError();
2303 }
2304
Sam Panzer0f384432012-08-21 00:52:01 +00002305 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2306 "invalid range expression in for loop");
2307
2308 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002309 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2310 if (!Context.hasSameType(BeginType, EndType)) {
2311 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2312 << BeginType << EndType;
2313 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2314 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2315 }
2316
2317 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2318 // Claim the type doesn't contain auto: we've already done the checking.
2319 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002320 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002321 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002322 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2323
Ted Kremenekbed648e2011-10-10 22:36:28 +00002324 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2325 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002326 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002327 if (BeginRef.isInvalid())
2328 return StmtError();
2329
Richard Smith02e85f32011-04-14 22:09:26 +00002330 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2331 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002332 if (EndRef.isInvalid())
2333 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002334
2335 // Build and check __begin != __end expression.
2336 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2337 BeginRef.get(), EndRef.get());
2338 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2339 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2340 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002341 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2342 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002343 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2344 if (!Context.hasSameType(BeginType, EndType))
2345 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2346 return StmtError();
2347 }
2348
2349 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002350 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2351 VK_LValue, ColonLoc);
2352 if (BeginRef.isInvalid())
2353 return StmtError();
2354
Richard Smith02e85f32011-04-14 22:09:26 +00002355 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002356 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Richard Smith9f690bd2015-10-27 06:02:45 +00002357 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002358 if (!IncrExpr.isInvalid())
2359 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002360 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002361 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2362 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002363 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2364 return StmtError();
2365 }
2366
2367 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002368 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2369 VK_LValue, ColonLoc);
2370 if (BeginRef.isInvalid())
2371 return StmtError();
2372
Richard Smith02e85f32011-04-14 22:09:26 +00002373 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2374 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002375 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2376 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002377 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2378 return StmtError();
2379 }
2380
Richard Smitha05b3b52012-09-20 21:52:32 +00002381 // Attach *__begin as initializer for VD. Don't touch it if we're just
2382 // trying to determine whether this would be a valid range.
2383 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002384 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2385 /*TypeMayContainAuto=*/true);
2386 if (LoopVar->isInvalidDecl())
2387 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2388 }
2389 }
2390
Richard Smitha05b3b52012-09-20 21:52:32 +00002391 // Don't bother to actually allocate the result if we're just trying to
2392 // determine whether it would be valid.
2393 if (Kind == BFRK_Check)
2394 return StmtResult();
2395
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002396 return new (Context) CXXForRangeStmt(
2397 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002398 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2399 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002400}
2401
Chad Rosier02a84392012-08-10 17:56:09 +00002402/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002403/// statement.
2404StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2405 if (!S || !B)
2406 return StmtError();
2407 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002408
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002409 ForStmt->setBody(B);
2410 return S;
2411}
2412
Richard Trieu3e1d4832015-04-13 22:08:55 +00002413// Warn when the loop variable is a const reference that creates a copy.
2414// Suggest using the non-reference type for copies. If a copy can be prevented
2415// suggest the const reference type that would do so.
2416// For instance, given "for (const &Foo : Range)", suggest
2417// "for (const Foo : Range)" to denote a copy is made for the loop. If
2418// possible, also suggest "for (const &Bar : Range)" if this type prevents
2419// the copy altogether.
2420static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2421 const VarDecl *VD,
2422 QualType RangeInitType) {
2423 const Expr *InitExpr = VD->getInit();
2424 if (!InitExpr)
2425 return;
2426
2427 QualType VariableType = VD->getType();
2428
2429 const MaterializeTemporaryExpr *MTE =
2430 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2431
2432 // No copy made.
2433 if (!MTE)
2434 return;
2435
2436 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2437
2438 // Searching for either UnaryOperator for dereference of a pointer or
2439 // CXXOperatorCallExpr for handling iterators.
2440 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2441 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2442 E = CCE->getArg(0);
2443 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2444 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2445 E = ME->getBase();
2446 } else {
2447 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2448 E = MTE->GetTemporaryExpr();
2449 }
2450 E = E->IgnoreImpCasts();
2451 }
2452
2453 bool ReturnsReference = false;
2454 if (isa<UnaryOperator>(E)) {
2455 ReturnsReference = true;
2456 } else {
2457 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2458 const FunctionDecl *FD = Call->getDirectCallee();
2459 QualType ReturnType = FD->getReturnType();
2460 ReturnsReference = ReturnType->isReferenceType();
2461 }
2462
2463 if (ReturnsReference) {
2464 // Loop variable creates a temporary. Suggest either to go with
2465 // non-reference loop variable to indiciate a copy is made, or
2466 // the correct time to bind a const reference.
2467 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2468 << VD << VariableType << E->getType();
2469 QualType NonReferenceType = VariableType.getNonReferenceType();
2470 NonReferenceType.removeLocalConst();
2471 QualType NewReferenceType =
2472 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2473 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2474 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2475 } else {
2476 // The range always returns a copy, so a temporary is always created.
2477 // Suggest removing the reference from the loop variable.
2478 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2479 << VD << RangeInitType;
2480 QualType NonReferenceType = VariableType.getNonReferenceType();
2481 NonReferenceType.removeLocalConst();
2482 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2483 << NonReferenceType << VD->getSourceRange();
2484 }
2485}
2486
2487// Warns when the loop variable can be changed to a reference type to
2488// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2489// "for (const Foo &x : Range)" if this form does not make a copy.
2490static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2491 const VarDecl *VD) {
2492 const Expr *InitExpr = VD->getInit();
2493 if (!InitExpr)
2494 return;
2495
2496 QualType VariableType = VD->getType();
2497
2498 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2499 if (!CE->getConstructor()->isCopyConstructor())
2500 return;
2501 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2502 if (CE->getCastKind() != CK_LValueToRValue)
2503 return;
2504 } else {
2505 return;
2506 }
2507
2508 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2509 // should be emitted. Also, only ignore POD types with trivial copy
2510 // constructors.
2511 if (VariableType.isPODType(SemaRef.Context))
2512 return;
2513
2514 // Suggest changing from a const variable to a const reference variable
2515 // if doing so will prevent a copy.
2516 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2517 << VD << VariableType << InitExpr->getType();
2518 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2519 << SemaRef.Context.getLValueReferenceType(VariableType)
2520 << VD->getSourceRange();
2521}
2522
2523/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2524/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2525/// using "const foo x" to show that a copy is made
2526/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2527/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2528/// prevent the copy.
2529/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2530/// Suggest "const foo &x" to prevent the copy.
2531static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2532 const CXXForRangeStmt *ForStmt) {
2533 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2534 ForStmt->getLocStart()) &&
2535 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2536 ForStmt->getLocStart()) &&
2537 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2538 ForStmt->getLocStart())) {
2539 return;
2540 }
2541
2542 const VarDecl *VD = ForStmt->getLoopVariable();
2543 if (!VD)
2544 return;
2545
2546 QualType VariableType = VD->getType();
2547
2548 if (VariableType->isIncompleteType())
2549 return;
2550
2551 const Expr *InitExpr = VD->getInit();
2552 if (!InitExpr)
2553 return;
2554
2555 if (VariableType->isReferenceType()) {
2556 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2557 ForStmt->getRangeInit()->getType());
2558 } else if (VariableType.isConstQualified()) {
2559 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2560 }
2561}
2562
Richard Smith02e85f32011-04-14 22:09:26 +00002563/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2564/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2565/// body cannot be performed until after the type of the range variable is
2566/// determined.
2567StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2568 if (!S || !B)
2569 return StmtError();
2570
Fariborz Jahanian00213472012-07-06 19:04:04 +00002571 if (isa<ObjCForCollectionStmt>(S))
2572 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002573
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002574 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2575 ForStmt->setBody(B);
2576
2577 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2578 diag::warn_empty_range_based_for_body);
2579
Richard Trieu3e1d4832015-04-13 22:08:55 +00002580 DiagnoseForRangeVariableCopies(*this, ForStmt);
2581
Richard Smith02e85f32011-04-14 22:09:26 +00002582 return S;
2583}
2584
Chris Lattnercab02a62011-02-17 20:34:02 +00002585StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2586 SourceLocation LabelLoc,
2587 LabelDecl *TheDecl) {
2588 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002589 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002590 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002591}
Chris Lattner1c310502007-05-31 06:00:00 +00002592
John McCalldadc5752010-08-24 06:29:42 +00002593StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002594Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002595 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002596 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002597 if (!E->isTypeDependent()) {
2598 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002599 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002600 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002601 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002602 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2603 if (ExprRes.isInvalid())
2604 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002605 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002606 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002607 return StmtError();
2608 }
John McCalla95172b2010-08-01 00:26:45 +00002609
Richard Smith945f8d32013-01-14 22:39:08 +00002610 ExprResult ExprRes = ActOnFinishFullExpr(E);
2611 if (ExprRes.isInvalid())
2612 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002613 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002614
John McCallaab3e412010-08-25 08:40:02 +00002615 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002616
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002617 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002618}
2619
Nico Weberd64657f2015-03-09 02:47:59 +00002620static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2621 const Scope &DestScope) {
2622 if (!S.CurrentSEHFinally.empty() &&
2623 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2624 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2625 }
2626}
2627
John McCalldadc5752010-08-24 06:29:42 +00002628StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002629Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002630 Scope *S = CurScope->getContinueParent();
2631 if (!S) {
2632 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002633 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002634 }
Nico Weberd64657f2015-03-09 02:47:59 +00002635 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002636
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002637 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002638}
2639
John McCalldadc5752010-08-24 06:29:42 +00002640StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002641Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002642 Scope *S = CurScope->getBreakParent();
2643 if (!S) {
2644 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002645 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002646 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002647 if (S->isOpenMPLoopScope())
2648 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2649 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002650 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002651
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002652 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002653}
2654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002656/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002657///
Douglas Gregor5d369002011-01-21 18:05:27 +00002658/// \param ReturnType If we're determining the copy elision candidate for
2659/// a return statement, this is the return type of the function. If we're
2660/// determining the copy elision candidate for a throw expression, this will
2661/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002662///
Douglas Gregor5d369002011-01-21 18:05:27 +00002663/// \param E The expression being returned from the function or block, or
2664/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002665///
Douglas Gregor86394412011-05-20 15:00:53 +00002666/// \param AllowFunctionParameter Whether we allow function parameters to
2667/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2668/// we re-use this logic to determine whether we should try to move as part of
2669/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002670///
2671/// \returns The NRVO candidate variable, if the return statement may use the
2672/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002673VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2674 Expr *E,
2675 bool AllowFunctionParameter) {
2676 if (!getLangOpts().CPlusPlus)
2677 return nullptr;
2678
2679 // - in a return statement in a function [where] ...
2680 // ... the expression is the name of a non-volatile automatic object ...
2681 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002682 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002683 return nullptr;
2684 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2685 if (!VD)
2686 return nullptr;
2687
2688 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2689 return VD;
2690 return nullptr;
2691}
2692
2693bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2694 bool AllowFunctionParameter) {
2695 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002696 // - in a return statement in a function with ...
2697 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002698 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002699 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002700 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002701 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002702 if (!VDType->isDependentType() &&
2703 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2704 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706
John McCall03318c12011-11-11 03:57:31 +00002707 // ...object (other than a function or catch-clause parameter)...
2708 if (VD->getKind() != Decl::Var &&
2709 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002710 return false;
2711 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002712
John McCall03318c12011-11-11 03:57:31 +00002713 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002714 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002715
2716 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002717 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002718
2719 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002720 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002721
2722 // Variables with higher required alignment than their type's ABI
2723 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002724 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002725 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002726 return false;
John McCall03318c12011-11-11 03:57:31 +00002727
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002728 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002729}
2730
Douglas Gregor626fbed2011-01-21 21:08:57 +00002731/// \brief Perform the initialization of a potentially-movable value, which
2732/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002733///
2734/// This routine implements C++0x [class.copy]p33, which attempts to treat
2735/// returned lvalues as rvalues in certain cases (to prefer move construction),
2736/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002737ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002738Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2739 const VarDecl *NRVOCandidate,
2740 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002741 Expr *Value,
2742 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002743 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744 // When the criteria for elision of a copy operation are met or would
2745 // be met save for the fact that the source object is a function
2746 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002747 // overload resolution to select the constructor for the copy is first
2748 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002749 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002750 if (AllowNRVO &&
2751 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002753 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002754
Douglas Gregorf282a762011-01-21 19:38:21 +00002755 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002756 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002757 = InitializationKind::CreateCopy(Value->getLocStart(),
2758 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002759 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760
2761 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002762 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002763 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002764 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002765 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002766 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2767 StepEnd = Seq.step_end();
2768 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002769 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002770 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002771
2772 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002773 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002774
Douglas Gregorf282a762011-01-21 19:38:21 +00002775 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002776 = Constructor->getParamDecl(0)->getType()
2777 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002778
Douglas Gregorf282a762011-01-21 19:38:21 +00002779 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002781 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2782 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002783 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784
Douglas Gregorf282a762011-01-21 19:38:21 +00002785 // Promote "AsRvalue" to the heap, since we now need this
2786 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002787 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002788 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789
Douglas Gregorf282a762011-01-21 19:38:21 +00002790 // Complete type-checking the initialization of the return type
2791 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002792 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002793 }
2794 }
2795 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002796
Douglas Gregorf282a762011-01-21 19:38:21 +00002797 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002799 // (again) now with the return value expression as written.
2800 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002801 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802
Douglas Gregorf282a762011-01-21 19:38:21 +00002803 return Res;
2804}
2805
Richard Smith4db51c22013-09-25 05:02:54 +00002806/// \brief Determine whether the declared return type of the specified function
2807/// contains 'auto'.
2808static bool hasDeducedReturnType(FunctionDecl *FD) {
2809 const FunctionProtoType *FPT =
2810 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002811 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002812}
2813
Eli Friedman34b49062012-01-26 03:00:14 +00002814/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2815/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002816///
John McCalldadc5752010-08-24 06:29:42 +00002817StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002818Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2819 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002820 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002821 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002822 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002823 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002824
Richard Smith4db51c22013-09-25 05:02:54 +00002825 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2826 // In C++1y, the return type may involve 'auto'.
2827 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2828 FunctionDecl *FD = CurLambda->CallOperator;
2829 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002830 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002831
2832 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2833 assert(AT && "lost auto type from lambda return type");
2834 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2835 FD->setInvalidDecl();
2836 return StmtError();
2837 }
Alp Toker314cc812014-01-25 16:55:45 +00002838 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002839 } else if (CurCap->HasImplicitReturnType) {
2840 // For blocks/lambdas with implicit return types, we check each return
2841 // statement individually, and deduce the common return type when the block
2842 // or lambda is completed.
2843 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002844 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002845 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2846 if (Result.isInvalid())
2847 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002848 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002849
Richard Smith5a0e50c2014-12-19 22:10:51 +00002850 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2851 // when deducing a return type for a lambda-expression (or by extension
2852 // for a block). These rules differ from the stated C++11 rules only in
2853 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002854 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002855 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002856 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002857 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002858 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002859 if (RetValExp) {
2860 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2861 // initializer list, because it is not an expression (even
2862 // though we represent it as one). We still deduce 'void'.
2863 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2864 << RetValExp->getSourceRange();
2865 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002866
Jordan Rosed39e5f12012-07-02 21:19:23 +00002867 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002868 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002869
2870 // Although we'll properly infer the type of the block once it's completed,
2871 // make sure we provide a return type now for better error recovery.
2872 if (CurCap->ReturnType.isNull())
2873 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002874 }
Eli Friedman34b49062012-01-26 03:00:14 +00002875 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002876
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002877 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002878 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2879 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2880 return StmtError();
2881 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002882 } else if (CapturedRegionScopeInfo *CurRegion =
2883 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2884 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2885 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002886 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002887 assert(CurLambda && "unknown kind of captured scope");
2888 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2889 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002890 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2891 return StmtError();
2892 }
2893 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002894
Steve Naroffc540d662008-09-03 18:15:37 +00002895 // Otherwise, verify that this result type matches the previous one. We are
2896 // pickier with blocks than for normal functions because we don't have GCC
2897 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002898 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002899 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002900 // Delay processing for now. TODO: there are lots of dependent
2901 // types we can conclusively prove aren't void.
2902 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002903 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002904 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002905 (RetValExp->isTypeDependent() ||
2906 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002907 if (!getLangOpts().CPlusPlus &&
2908 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002909 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002910 else {
2911 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002912 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002913 }
Steve Naroffc540d662008-09-03 18:15:37 +00002914 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002915 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002916 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2917 } else if (!RetValExp->isTypeDependent()) {
2918 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002919
John McCall5500ef22011-08-17 22:09:46 +00002920 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2921 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2922 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002923
John McCall5500ef22011-08-17 22:09:46 +00002924 // In C++ the return statement is handled via a copy initialization.
2925 // the C version of which boils down to CheckSingleAssignmentConstraints.
2926 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2927 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2928 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002929 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002930 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2931 FnRetType, RetValExp);
2932 if (Res.isInvalid()) {
2933 // FIXME: Cleanup temporaries here, anyway?
2934 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002935 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002936 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002937 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002938 } else {
2939 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002940 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002941
John McCall75f92b52011-08-17 21:34:14 +00002942 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002943 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2944 if (ER.isInvalid())
2945 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002946 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002947 }
John McCall5500ef22011-08-17 22:09:46 +00002948 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2949 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002950
Jordan Rosed39e5f12012-07-02 21:19:23 +00002951 // If we need to check for the named return value optimization,
2952 // or if we need to infer the return type,
2953 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002954 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002955 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956
Richard Smith9f690bd2015-10-27 06:02:45 +00002957 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
2958 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
2959
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002960 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002961}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002962
Nico Weber72889432014-09-06 01:25:55 +00002963namespace {
2964/// \brief Marks all typedefs in all local classes in a type referenced.
2965///
2966/// In a function like
2967/// auto f() {
2968/// struct S { typedef int a; };
2969/// return S();
2970/// }
2971///
2972/// the local type escapes and could be referenced in some TUs but not in
2973/// others. Pretend that all local typedefs are always referenced, to not warn
2974/// on this. This isn't necessary if f has internal linkage, or the typedef
2975/// is private.
2976class LocalTypedefNameReferencer
2977 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2978public:
2979 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2980 bool VisitRecordType(const RecordType *RT);
2981private:
2982 Sema &S;
2983};
2984bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2985 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2986 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2987 R->isDependentType())
2988 return true;
2989 for (auto *TmpD : R->decls())
2990 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2991 if (T->getAccess() != AS_private || R->hasFriends())
2992 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2993 return true;
2994}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002995}
Nico Weber72889432014-09-06 01:25:55 +00002996
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002997TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002998 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002999 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3000 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003001 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003002}
3003
Richard Smith2a7d4812013-05-04 07:00:32 +00003004/// Deduce the return type for a function from a returned expression, per
3005/// C++1y [dcl.spec.auto]p6.
3006bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3007 SourceLocation ReturnLoc,
3008 Expr *&RetExpr,
3009 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003010 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003011 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003012
Richard Smithc58f38f2013-08-14 20:16:31 +00003013 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3014 // If the deduction is for a return statement and the initializer is
3015 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003016 Diag(RetExpr->getExprLoc(),
3017 getCurLambda() ? diag::err_lambda_return_init_list
3018 : diag::err_auto_fn_return_init_list)
3019 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003020 return true;
3021 }
3022
3023 if (FD->isDependentContext()) {
3024 // C++1y [dcl.spec.auto]p12:
3025 // Return type deduction [...] occurs when the definition is
3026 // instantiated even if the function body contains a return
3027 // statement with a non-type-dependent operand.
3028 assert(AT->isDeduced() && "should have deduced to dependent type");
3029 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003030 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003031
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003032 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003033 // Otherwise, [...] deduce a value for U using the rules of template
3034 // argument deduction.
3035 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3036
3037 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3038 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3039 << OrigResultType.getType() << RetExpr->getType();
3040
3041 if (DAR != DAR_Succeeded)
3042 return true;
Nico Weber72889432014-09-06 01:25:55 +00003043
3044 // If a local type is part of the returned type, mark its fields as
3045 // referenced.
3046 LocalTypedefNameReferencer Referencer(*this);
3047 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003048 } else {
3049 // In the case of a return with no operand, the initializer is considered
3050 // to be void().
3051 //
3052 // Deduction here can only succeed if the return type is exactly 'cv auto'
3053 // or 'decltype(auto)', so just check for that case directly.
3054 if (!OrigResultType.getType()->getAs<AutoType>()) {
3055 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3056 << OrigResultType.getType();
3057 return true;
3058 }
3059 // We always deduce U = void in this case.
3060 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3061 if (Deduced.isNull())
3062 return true;
3063 }
3064
3065 // If a function with a declared return type that contains a placeholder type
3066 // has multiple return statements, the return type is deduced for each return
3067 // statement. [...] if the type deduced is not the same in each deduction,
3068 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003069 QualType DeducedT = AT->getDeducedType();
3070 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003071 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003072 // It is possible that NewAT->getDeducedType() is null. When that happens,
3073 // we should not crash, instead we ignore this deduction.
3074 if (NewAT->getDeducedType().isNull())
3075 return false;
3076
Douglas Gregora602a152015-10-01 20:20:47 +00003077 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003078 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003079 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3080 NewAT->getDeducedType());
3081 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003082 const LambdaScopeInfo *LambdaSI = getCurLambda();
3083 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3084 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003085 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003086 << true /*IsLambda*/;
3087 } else {
3088 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3089 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003090 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003091 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003092 return true;
3093 }
3094 } else if (!FD->isInvalidDecl()) {
3095 // Update all declarations of the function to have the deduced return type.
3096 Context.adjustDeducedFunctionResultType(FD, Deduced);
3097 }
3098
3099 return false;
3100}
3101
John McCalldadc5752010-08-24 06:29:42 +00003102StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003103Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3104 Scope *CurScope) {
3105 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3106 if (R.isInvalid()) {
3107 return R;
3108 }
3109
3110 if (VarDecl *VD =
3111 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3112 CurScope->addNRVOCandidate(VD);
3113 } else {
3114 CurScope->setNoNRVO();
3115 }
3116
Nico Weberd64657f2015-03-09 02:47:59 +00003117 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3118
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003119 return R;
3120}
3121
3122StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003123 // Check for unexpanded parameter packs.
3124 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3125 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003126
Eli Friedman34b49062012-01-26 03:00:14 +00003127 if (isa<CapturingScopeInfo>(getCurFunction()))
3128 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003129
Chris Lattner79413952008-12-04 23:50:19 +00003130 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003131 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003132 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003133 bool isObjCMethod = false;
3134
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003135 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003136 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003137 if (FD->hasAttrs())
3138 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003139 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003140 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003141 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003142 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003143 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003144 isObjCMethod = true;
3145 if (MD->hasAttrs())
3146 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003147 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3148 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003149 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003150 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003151 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3152 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003153 }
3154 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003155 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003156
Richard Smith2a7d4812013-05-04 07:00:32 +00003157 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3158 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003159 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003160 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3161 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003162 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003163 FD->setInvalidDecl();
3164 return StmtError();
3165 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003166 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003167 }
3168 }
3169 }
3170
Richard Smithc58f38f2013-08-14 20:16:31 +00003171 bool HasDependentReturnType = FnRetType->isDependentType();
3172
Craig Topperc3ec1492014-05-26 06:22:03 +00003173 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003174 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003175 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003176 if (isa<InitListExpr>(RetValExp)) {
3177 // We simply never allow init lists as the return value of void
3178 // functions. This is compatible because this was never allowed before,
3179 // so there's no legacy code to deal with.
3180 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3181 int FunctionKind = 0;
3182 if (isa<ObjCMethodDecl>(CurDecl))
3183 FunctionKind = 1;
3184 else if (isa<CXXConstructorDecl>(CurDecl))
3185 FunctionKind = 2;
3186 else if (isa<CXXDestructorDecl>(CurDecl))
3187 FunctionKind = 3;
3188
3189 Diag(ReturnLoc, diag::err_return_init_list)
3190 << CurDecl->getDeclName() << FunctionKind
3191 << RetValExp->getSourceRange();
3192
3193 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003194 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003195 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003196 // C99 6.8.6.4p1 (ext_ since GCC warns)
3197 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003198 if (RetValExp->getType()->isVoidType()) {
3199 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3200 if (isa<CXXConstructorDecl>(CurDecl) ||
3201 isa<CXXDestructorDecl>(CurDecl))
3202 D = diag::err_ctor_dtor_returns_void;
3203 else
3204 D = diag::ext_return_has_void_expr;
3205 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003206 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003207 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003208 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003209 if (Result.isInvalid())
3210 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003211 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003212 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003213 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003214 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003215 // return of void in constructor/destructor is illegal in C++.
3216 if (D == diag::err_ctor_dtor_returns_void) {
3217 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3218 Diag(ReturnLoc, D)
3219 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3220 << RetValExp->getSourceRange();
3221 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003222 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003223 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003224 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003225 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003226
3227 int FunctionKind = 0;
3228 if (isa<ObjCMethodDecl>(CurDecl))
3229 FunctionKind = 1;
3230 else if (isa<CXXConstructorDecl>(CurDecl))
3231 FunctionKind = 2;
3232 else if (isa<CXXDestructorDecl>(CurDecl))
3233 FunctionKind = 3;
3234
Nick Lewycky1be750a2011-06-01 07:44:31 +00003235 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003236 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003237 << RetValExp->getSourceRange();
3238 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
Sebastian Redleef474c2012-02-22 10:50:08 +00003241 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003242 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3243 if (ER.isInvalid())
3244 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003245 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003246 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Craig Topperc3ec1492014-05-26 06:22:03 +00003249 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003250 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003251 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003252
David Majnemer2887ad32014-12-13 08:12:56 +00003253 unsigned DiagID;
3254 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3255 // C++11 [stmt.return]p2
3256 DiagID = diag::err_constexpr_return_missing_expr;
3257 FD->setInvalidDecl();
3258 } else if (getLangOpts().C99) {
3259 // C99 6.8.6.4p1 (ext_ since GCC warns)
3260 DiagID = diag::ext_return_missing_expr;
3261 } else {
3262 // C90 6.6.6.4p4
3263 DiagID = diag::warn_return_missing_expr;
3264 }
3265
3266 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003267 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003268 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003269 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003270
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003271 Result = new (Context) ReturnStmt(ReturnLoc);
3272 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003273 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003274 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003275
3276 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3277
3278 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3279 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3280 // function return.
3281
3282 // In C++ the return statement is handled via a copy initialization,
3283 // the C version of which boils down to CheckSingleAssignmentConstraints.
3284 if (RetValExp)
3285 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003286 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003287 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003289 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003290 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003291 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003292 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003293 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003294 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003295 return StmtError();
3296 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003297 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003298
3299 // If we have a related result type, we need to implicitly
3300 // convert back to the formal result type. We can't pretend to
3301 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003302 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003303 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003304 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3305 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003306 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3307 if (Res.isInvalid()) {
3308 // FIXME: Clean up temporaries here anyway?
3309 return StmtError();
3310 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003311 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003312 }
3313
Artyom Skrobov9f213442014-01-24 11:10:39 +00003314 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3315 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317
John McCallacf0ee52010-10-08 02:01:28 +00003318 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003319 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3320 if (ER.isInvalid())
3321 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003322 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003323 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003324 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326
3327 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003328 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003329 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003330 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003331
Richard Smith9f690bd2015-10-27 06:02:45 +00003332 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3333 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3334
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003335 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003336}
3337
John McCalldadc5752010-08-24 06:29:42 +00003338StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003339Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003340 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003341 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003342 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003343 if (Var && Var->isInvalidDecl())
3344 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003346 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003347}
3348
John McCalldadc5752010-08-24 06:29:42 +00003349StmtResult
John McCallb268a282010-08-23 23:25:46 +00003350Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003351 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003352}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003353
John McCalldadc5752010-08-24 06:29:42 +00003354StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003356 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003357 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003358 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3359
John McCallaab3e412010-08-25 08:40:02 +00003360 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003361 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003362 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3363 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003364}
3365
John McCall0bd3e402012-05-08 21:41:25 +00003366StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003367 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003368 ExprResult Result = DefaultLvalueConversion(Throw);
3369 if (Result.isInvalid())
3370 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003371
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003372 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003373 if (Result.isInvalid())
3374 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003375 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003376
Douglas Gregor2900c162010-04-22 21:44:01 +00003377 QualType ThrowType = Throw->getType();
3378 // Make sure the expression type is an ObjC pointer or "void *".
3379 if (!ThrowType->isDependentType() &&
3380 !ThrowType->isObjCObjectPointerType()) {
3381 const PointerType *PT = ThrowType->getAs<PointerType>();
3382 if (!PT || !PT->getPointeeType()->isVoidType())
3383 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3384 << Throw->getType() << Throw->getSourceRange());
3385 }
3386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003388 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003389}
3390
John McCalldadc5752010-08-24 06:29:42 +00003391StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003393 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003394 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003395 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3396
John McCallb268a282010-08-23 23:25:46 +00003397 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003398 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003399 // in the context of an @catch clause).
3400 Scope *AtCatchParent = CurScope;
3401 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3402 AtCatchParent = AtCatchParent->getParent();
3403 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003404 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 }
John McCallb268a282010-08-23 23:25:46 +00003406 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003407}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003408
John McCalld9bb7432011-07-27 21:50:02 +00003409ExprResult
3410Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3411 ExprResult result = DefaultLvalueConversion(operand);
3412 if (result.isInvalid())
3413 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003414 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003415
3416 // Make sure the expression type is an ObjC pointer or "void *".
3417 QualType type = operand->getType();
3418 if (!type->isDependentType() &&
3419 !type->isObjCObjectPointerType()) {
3420 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003421 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3422 if (getLangOpts().CPlusPlus) {
3423 if (RequireCompleteType(atLoc, type,
3424 diag::err_incomplete_receiver_type))
3425 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3426 << type << operand->getSourceRange();
3427
3428 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3429 if (!result.isUsable())
3430 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3431 << type << operand->getSourceRange();
3432
3433 operand = result.get();
3434 } else {
3435 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3436 << type << operand->getSourceRange();
3437 }
3438 }
John McCalld9bb7432011-07-27 21:50:02 +00003439 }
3440
3441 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003442 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003443}
3444
John McCalldadc5752010-08-24 06:29:42 +00003445StmtResult
John McCallb268a282010-08-23 23:25:46 +00003446Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3447 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003448 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003449 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003450 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003451}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003452
3453/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3454/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003455StmtResult
John McCall48871652010-08-21 09:40:31 +00003456Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003457 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003458 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003459 return new (Context)
3460 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003461}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003462
John McCall31168b02011-06-15 23:02:42 +00003463StmtResult
3464Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3465 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003466 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003467}
3468
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003469namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003470class CatchHandlerType {
3471 QualType QT;
3472 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003473
Aaron Ballman8aee642902015-04-08 00:05:29 +00003474 // This is a special constructor to be used only with DenseMapInfo's
3475 // getEmptyKey() and getTombstoneKey() functions.
3476 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3477 enum Unique { ForDenseMap };
3478 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3479
Sebastian Redl63c4da02009-07-29 17:15:45 +00003480public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003481 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003482 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003483 /// level pointer and cv-qualifiers.
3484 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3485 if (QT->isPointerType())
3486 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003487
Aaron Ballman8aee642902015-04-08 00:05:29 +00003488 if (IsPointer || QT->isReferenceType())
3489 QT = QT->getPointeeType();
3490 QT = QT.getUnqualifiedType();
3491 }
3492
3493 /// Used when creating a CatchHandlerType from a base class type; pretends the
3494 /// type passed in had the pointer qualifier, does not need to get an
3495 /// unqualified type.
3496 CatchHandlerType(QualType QT, bool IsPointer)
3497 : QT(QT), IsPointer(IsPointer) {}
3498
3499 QualType underlying() const { return QT; }
3500 bool isPointer() const { return IsPointer; }
3501
3502 friend bool operator==(const CatchHandlerType &LHS,
3503 const CatchHandlerType &RHS) {
3504 // If the pointer qualification does not match, we can return early.
3505 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003506 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003507 // Otherwise, check the underlying type without cv-qualifiers.
3508 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003509 }
3510};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003511} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003512
Aaron Ballman8aee642902015-04-08 00:05:29 +00003513namespace llvm {
3514template <> struct DenseMapInfo<CatchHandlerType> {
3515 static CatchHandlerType getEmptyKey() {
3516 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3517 CatchHandlerType::ForDenseMap);
3518 }
3519
3520 static CatchHandlerType getTombstoneKey() {
3521 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3522 CatchHandlerType::ForDenseMap);
3523 }
3524
3525 static unsigned getHashValue(const CatchHandlerType &Base) {
3526 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3527 }
3528
3529 static bool isEqual(const CatchHandlerType &LHS,
3530 const CatchHandlerType &RHS) {
3531 return LHS == RHS;
3532 }
3533};
3534
3535// It's OK to treat CatchHandlerType as a POD type.
3536template <> struct isPodLike<CatchHandlerType> {
3537 static const bool value = true;
3538};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003539}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003540
3541namespace {
3542class CatchTypePublicBases {
3543 ASTContext &Ctx;
3544 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3545 const bool CheckAgainstPointer;
3546
3547 CXXCatchStmt *FoundHandler;
3548 CanQualType FoundHandlerType;
3549
3550public:
3551 CatchTypePublicBases(
3552 ASTContext &Ctx,
3553 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3554 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3555 FoundHandler(nullptr) {}
3556
3557 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3558 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3559
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003560 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003561 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003562 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3563 auto M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003564 auto I = M.find(Check);
3565 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003566 FoundHandler = I->second;
3567 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003568 return true;
3569 }
3570 }
3571 return false;
3572 }
3573};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003574}
Dan Gohman28ade552010-07-26 21:25:24 +00003575
Sebastian Redl9b244a82008-12-22 21:35:02 +00003576/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3577/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003578StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3579 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003580 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003582 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003583 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003584
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003585 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3586 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3587
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003588 sema::FunctionScopeInfo *FSI = getCurFunction();
3589
Reid Klecknere7175912015-02-02 22:15:31 +00003590 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003591 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003592 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003593 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003594 }
3595
Robert Wilhelmcafda822013-08-22 09:20:03 +00003596 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003597 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003598 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003599
Aaron Ballman8aee642902015-04-08 00:05:29 +00003600 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003601 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003602 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003603
Aaron Ballman8aee642902015-04-08 00:05:29 +00003604 // Diagnose when the handler is a catch-all handler, but it isn't the last
3605 // handler for the try block. [except.handle]p5. Also, skip exception
3606 // declarations that are invalid, since we can't usefully report on them.
3607 if (!H->getExceptionDecl()) {
3608 if (i < NumHandlers - 1)
3609 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003610 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003611 } else if (H->getExceptionDecl()->isInvalidDecl())
3612 continue;
3613
3614 // Walk the type hierarchy to diagnose when this type has already been
3615 // handled (duplication), or cannot be handled (derivation inversion). We
3616 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003617 CatchHandlerType HandlerCHT =
3618 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003619
3620 // We can ignore whether the type is a reference or a pointer; we need the
3621 // underlying declaration type in order to get at the underlying record
3622 // decl, if there is one.
3623 QualType Underlying = HandlerCHT.underlying();
3624 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3625 if (!RD->hasDefinition())
3626 continue;
3627 // Check that none of the public, unambiguous base classes are in the
3628 // map ([except.handle]p1). Give the base classes the same pointer
3629 // qualification as the original type we are basing off of. This allows
3630 // comparison against the handler type using the same top-level pointer
3631 // as the original type.
3632 CXXBasePaths Paths;
3633 Paths.setOrigin(RD);
3634 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003635 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003636 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3637 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3638 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3639 diag::warn_exception_caught_by_earlier_handler)
3640 << H->getCaughtType();
3641 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3642 diag::note_previous_exception_handler)
3643 << Problem->getCaughtType();
3644 }
3645 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003646 }
Mike Stump11289f42009-09-09 15:08:12 +00003647
Aaron Ballman8aee642902015-04-08 00:05:29 +00003648 // Add the type the list of ones we have handled; diagnose if we've already
3649 // handled it.
3650 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3651 if (!R.second) {
3652 const CXXCatchStmt *Problem = R.first->second;
3653 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3654 diag::warn_exception_caught_by_earlier_handler)
3655 << H->getCaughtType();
3656 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3657 diag::note_previous_exception_handler)
3658 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003659 }
3660 }
Mike Stump11289f42009-09-09 15:08:12 +00003661
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003662 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003663
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003664 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003665}
John Wiegley1c0675e2011-04-28 01:08:34 +00003666
Reid Klecknere7175912015-02-02 22:15:31 +00003667StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3668 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003669 assert(TryBlock && Handler);
3670
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003671 sema::FunctionScopeInfo *FSI = getCurFunction();
3672
Reid Klecknere7175912015-02-02 22:15:31 +00003673 // SEH __try is incompatible with C++ try. Borland appears to support this,
3674 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003675 if (!getLangOpts().Borland) {
3676 if (FSI->FirstCXXTryLoc.isValid()) {
3677 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3678 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3679 }
Reid Klecknere7175912015-02-02 22:15:31 +00003680 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003681
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003682 FSI->setHasSEHTry(TryLoc);
3683
3684 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3685 // track if they use SEH.
3686 DeclContext *DC = CurContext;
3687 while (DC && !DC->isFunctionOrMethod())
3688 DC = DC->getParent();
3689 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3690 if (FD)
3691 FD->setUsesSEHTry(true);
3692 else
3693 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003694
Reid Kleckner8819a402015-07-10 00:16:25 +00003695 // Reject __try on unsupported targets.
3696 if (!Context.getTargetInfo().isSEHTrySupported())
3697 Diag(TryLoc, diag::err_seh_try_unsupported);
3698
Reid Klecknere7175912015-02-02 22:15:31 +00003699 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003700}
3701
3702StmtResult
3703Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3704 Expr *FilterExpr,
3705 Stmt *Block) {
3706 assert(FilterExpr && Block);
3707
3708 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003709 return StmtError(Diag(FilterExpr->getExprLoc(),
3710 diag::err_filter_expression_integral)
3711 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003712 }
3713
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003714 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003715}
3716
Nico Weberd64657f2015-03-09 02:47:59 +00003717void Sema::ActOnStartSEHFinallyBlock() {
3718 CurrentSEHFinally.push_back(CurScope);
3719}
3720
Nico Weberce903292015-03-09 03:17:15 +00003721void Sema::ActOnAbortSEHFinallyBlock() {
3722 CurrentSEHFinally.pop_back();
3723}
3724
Nico Weberd64657f2015-03-09 02:47:59 +00003725StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003726 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003727 CurrentSEHFinally.pop_back();
3728 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003729}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003730
Nico Weberc7d05962014-07-06 22:32:59 +00003731StmtResult
3732Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003733 Scope *SEHTryParent = CurScope;
3734 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3735 SEHTryParent = SEHTryParent->getParent();
3736 if (!SEHTryParent)
3737 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003738 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003739
Nico Weber9b982072014-07-07 00:12:30 +00003740 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003741}
3742
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003743StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3744 bool IsIfExists,
3745 NestedNameSpecifierLoc QualifierLoc,
3746 DeclarationNameInfo NameInfo,
3747 Stmt *Nested)
3748{
3749 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003750 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003751 cast<CompoundStmt>(Nested));
3752}
3753
3754
Chad Rosier02a84392012-08-10 17:56:09 +00003755StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003756 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003757 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003758 UnqualifiedId &Name,
3759 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003760 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003761 SS.getWithLocInContext(Context),
3762 GetNameFromUnqualifiedId(Name),
3763 Nested);
3764}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003765
3766RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003767Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3768 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003769 DeclContext *DC = CurContext;
3770 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3771 DC = DC->getParent();
3772
Craig Topperc3ec1492014-05-26 06:22:03 +00003773 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003774 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003775 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3776 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003777 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003778 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003779
Alexey Bataev330de032014-10-29 12:21:55 +00003780 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003781 DC->addDecl(RD);
3782 RD->setImplicit();
3783 RD->startDefinition();
3784
Alexey Bataev9959db52014-05-06 10:08:46 +00003785 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003786 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003787 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003788 return RD;
3789}
3790
3791static void buildCapturedStmtCaptureList(
3792 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3793 SmallVectorImpl<Expr *> &CaptureInits,
3794 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3795
3796 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3797 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3798
3799 if (Cap->isThisCapture()) {
3800 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3801 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003802 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003803 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003804 } else if (Cap->isVLATypeCapture()) {
3805 Captures.push_back(
3806 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3807 CaptureInits.push_back(nullptr);
3808 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003809 }
3810
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003811 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00003812 Cap->isReferenceCapture()
3813 ? CapturedStmt::VCK_ByRef
3814 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003815 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003816 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003817 }
3818}
3819
3820void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003821 CapturedRegionKind Kind,
3822 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003823 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003824 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003825
Alexey Bataev9959db52014-05-06 10:08:46 +00003826 // Build the context parameter
3827 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3828 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3829 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3830 ImplicitParamDecl *Param
3831 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3832 DC->addDecl(Param);
3833
3834 CD->setContextParam(0, Param);
3835
3836 // Enter the capturing scope for this captured region.
3837 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3838
3839 if (CurScope)
3840 PushDeclContext(CurScope, CD);
3841 else
3842 CurContext = CD;
3843
3844 PushExpressionEvaluationContext(PotentiallyEvaluated);
3845}
3846
3847void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3848 CapturedRegionKind Kind,
3849 ArrayRef<CapturedParamNameType> Params) {
3850 CapturedDecl *CD = nullptr;
3851 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3852
3853 // Build the context parameter
3854 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3855 bool ContextIsFound = false;
3856 unsigned ParamNum = 0;
3857 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3858 E = Params.end();
3859 I != E; ++I, ++ParamNum) {
3860 if (I->second.isNull()) {
3861 assert(!ContextIsFound &&
3862 "null type has been found already for '__context' parameter");
3863 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3864 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3865 ImplicitParamDecl *Param
3866 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3867 DC->addDecl(Param);
3868 CD->setContextParam(ParamNum, Param);
3869 ContextIsFound = true;
3870 } else {
3871 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3872 ImplicitParamDecl *Param
3873 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3874 DC->addDecl(Param);
3875 CD->setParam(ParamNum, Param);
3876 }
3877 }
3878 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003879 if (!ContextIsFound) {
3880 // Add __context implicitly if it is not specified.
3881 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3882 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3883 ImplicitParamDecl *Param =
3884 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3885 DC->addDecl(Param);
3886 CD->setContextParam(ParamNum, Param);
3887 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003888 // Enter the capturing scope for this captured region.
3889 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3890
3891 if (CurScope)
3892 PushDeclContext(CurScope, CD);
3893 else
3894 CurContext = CD;
3895
3896 PushExpressionEvaluationContext(PotentiallyEvaluated);
3897}
3898
Wei Pan17fbf6e2013-05-04 03:59:06 +00003899void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003900 DiscardCleanupsInEvaluationContext();
3901 PopExpressionEvaluationContext();
3902
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003903 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3904 RecordDecl *Record = RSI->TheRecordDecl;
3905 Record->setInvalidDecl();
3906
Aaron Ballman62e47c42014-03-10 13:43:55 +00003907 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003908 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3909 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003910
Wei Pan17fbf6e2013-05-04 03:59:06 +00003911 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003912 PopFunctionScopeInfo();
3913}
3914
3915StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3916 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3917
3918 SmallVector<CapturedStmt::Capture, 4> Captures;
3919 SmallVector<Expr *, 4> CaptureInits;
3920 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3921
3922 CapturedDecl *CD = RSI->TheCapturedDecl;
3923 RecordDecl *RD = RSI->TheRecordDecl;
3924
Wei Pan17fbf6e2013-05-04 03:59:06 +00003925 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3926 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003927 CaptureInits, CD, RD);
3928
3929 CD->setBody(Res->getCapturedStmt());
3930 RD->completeDefinition();
3931
Wei Pan17fbf6e2013-05-04 03:59:06 +00003932 DiscardCleanupsInEvaluationContext();
3933 PopExpressionEvaluationContext();
3934
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003935 PopDeclContext();
3936 PopFunctionScopeInfo();
3937
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003938 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003939}