blob: 2e1ea3e2f6487af3996ebc7e1f783791f3de63bf [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Erik Pilkingtonce26eac2016-04-26 20:55:48 +000040
Chris Lattneraf8d5812006-11-10 05:07:45 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000043
Richard Smith945f8d32013-01-14 22:39:08 +000044StmtResult Sema::ActOnExprStmt(ExprResult FE) {
45 if (FE.isInvalid())
46 return StmtError();
47
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
50 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000051 return StmtError();
52
Chris Lattner903eb512008-07-25 23:18:17 +000053 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000056
Chris Lattner903eb512008-07-25 23:18:17 +000057 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000058 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000059}
60
61
John McCalleaef89b2013-03-22 02:10:40 +000062StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
64 return StmtError();
65}
66
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000067StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000068 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000069 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000070}
71
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000072StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000074 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattnercbafe8d2009-04-12 20:13:14 +000076 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000079 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000080}
Chris Lattneraf8d5812006-11-10 05:07:45 +000081
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000082void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000083 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000084
Douglas Gregor2eb1c572013-04-08 20:52:24 +000085 // If we don't have a declaration, or we have an invalid declaration,
86 // just return.
87 if (DG.isNull() || !DG.isSingleDecl())
88 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000089
Douglas Gregor2eb1c572013-04-08 20:52:24 +000090 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
92 return;
93
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
96 if (!var) {
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
99 return;
100 }
John McCall31168b02011-06-15 23:02:42 +0000101
John McCalld4631322011-06-17 06:42:21 +0000102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000104 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000105
John McCalld4631322011-06-17 06:42:21 +0000106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000110 QualType type = var->getType();
111
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000119 }
120 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000121}
122
Richard Trieu99e1c952014-03-11 03:11:08 +0000123/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000125///
126/// Adding a cast to void (or other expression wrappers) will prevent the
127/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000128static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000130 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000133 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000134 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135
Richard Trieu99e1c952014-03-11 03:11:08 +0000136 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000137 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000141 switch (Op->getOperator()) {
142 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000143 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000144 case OO_EqualEqual:
145 case OO_ExclaimEqual:
146 IsRelational = false;
147 break;
148 case OO_Less:
149 case OO_Greater:
150 case OO_GreaterEqual:
151 case OO_LessEqual:
152 IsRelational = true;
153 break;
154 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else {
160 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000161 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000162 }
163
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000168
Chandler Carruthe2669392011-08-17 09:34:37 +0000169 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000171
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000174 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000175 if (IsNotEqual)
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
178 else
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
181 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000182
183 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000184}
185
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000186void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
189
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000190 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000191 if (!E)
192 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000193
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
197 return;
198
Nico Weber0e631632015-10-27 19:47:40 +0000199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208
Eli Friedmanc11535c2012-05-24 00:47:05 +0000209 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000210 SourceLocation Loc;
211 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000213 return;
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattner6dc7e572012-08-31 22:39:21 +0000215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
218 // false positive.
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
220 return;
221
Nico Weber0e631632015-10-27 19:47:40 +0000222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
228 return;
229 }
230
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
233 // cases now.
234 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000236 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000239
Chandler Carruthe2669392011-08-17 09:34:37 +0000240 if (DiagnoseUnusedComparison(*this, E))
241 return;
242
Eli Friedmanc11535c2012-05-24 00:47:05 +0000243 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000245 if (E->getType()->isVoidType())
246 return;
247
Chris Lattner1a6babf2009-10-13 04:53:48 +0000248 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
251 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000252 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000257 return;
258 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000259 if (ShouldSuppress)
260 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000261 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
263 return;
264 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000265 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
267 return;
268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000269 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000270 } else if (ShouldSuppress)
271 return;
272
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
276 return;
277 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000278 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000279 if (MD) {
Aaron Ballmane7964782016-03-07 22:44:55 +0000280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000282 return;
283 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000284 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
289 else
290 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
Daniel Jasper9c81a722017-03-27 16:29:41 +0000293 const Expr *E = FC->getSubExpr();
294 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
295 E = TE->getSubExpr();
296 if (isa<CXXTemporaryObjectExpr>(E))
Douglas Gregorb33eed02010-04-16 22:09:46 +0000297 return;
Daniel Jasper9c81a722017-03-27 16:29:41 +0000298 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
299 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
300 if (!RD->getAttr<WarnUnusedAttr>())
301 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000302 }
John McCall2351cb92010-04-06 22:24:14 +0000303 // Diagnose "(void*) blah" as a typo for "(void) blah".
304 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
305 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
306 QualType T = TI->getType();
307
308 // We really do want to use the non-canonical type here.
309 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000310 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000311
312 Diag(Loc, diag::warn_unused_voidptr)
313 << FixItHint::CreateRemoval(TL.getStarLoc());
314 return;
315 }
316 }
317
Eli Friedmanc11535c2012-05-24 00:47:05 +0000318 if (E->isGLValue() && E->getType().isVolatileQualified()) {
319 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
320 return;
321 }
322
Craig Topperc3ec1492014-05-26 06:22:03 +0000323 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000324}
325
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000326void Sema::ActOnStartOfCompoundStmt() {
327 PushCompoundScope();
328}
329
330void Sema::ActOnFinishOfCompoundStmt() {
331 PopCompoundScope();
332}
333
334sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
335 return getCurFunction()->CompoundScopes.back();
336}
337
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000338StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
339 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
340 const unsigned NumElts = Elts.size();
341
Chris Lattnerd864daf2007-08-27 04:29:41 +0000342 // If we're in C89 mode, check that we don't have any decls after stmts. If
343 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000344 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000345 // Note that __extension__ can be around a decl.
346 unsigned i = 0;
347 // Skip over all declarations.
348 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
349 /*empty*/;
350
351 // We found the end of the list or a statement. Scan for another declstmt.
352 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
353 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000354
Chris Lattnerd864daf2007-08-27 04:29:41 +0000355 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000356 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000357 Diag(D->getLocation(), diag::ext_mixed_decls_code);
358 }
359 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000360 // Warn about unused expressions in statements.
361 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000362 // Ignore statements that are last in a statement expression.
363 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000364 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000366 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000367 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000368
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000369 // Check for suspicious empty body (null statement) in `for' and `while'
370 // statements. Don't do anything for template instantiations, this just adds
371 // noise.
372 if (NumElts != 0 && !CurrentInstantiationScope &&
373 getCurCompoundScope().HasEmptyLoopBodies) {
374 for (unsigned i = 0; i != NumElts - 1; ++i)
375 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
376 }
377
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000378 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000379}
380
John McCalldadc5752010-08-24 06:29:42 +0000381StmtResult
John McCallb268a282010-08-23 23:25:46 +0000382Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
383 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000384 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000385 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000386
John McCallaab3e412010-08-25 08:40:02 +0000387 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000388 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000389 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000390 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000391
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000392 ExprResult LHS =
393 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
394 if (!getLangOpts().CPlusPlus11)
395 return VerifyIntegerConstantExpression(E);
396 if (Expr *CondExpr =
397 getCurFunction()->SwitchStack.back()->getCond()) {
398 QualType CondType = CondExpr->getType();
399 llvm::APSInt TempVal;
400 return CheckConvertedConstantExpression(E, CondType, TempVal,
401 CCEK_CaseValue);
402 }
403 return ExprError();
404 });
405 if (LHS.isInvalid())
406 return StmtError();
407 LHSVal = LHS.get();
408
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000409 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000410 // C99 6.8.4.2p3: The expression shall be an integer constant.
411 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000412 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000413 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000414 if (!LHSVal)
415 return StmtError();
416 }
Richard Smithf8379a02012-01-18 23:55:52 +0000417
418 // GCC extension: The expression shall be an integer constant.
419
Richard Smithf4c51d92012-02-04 09:53:13 +0000420 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000422 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000423 }
424 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000425
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000426 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000427 getLangOpts().CPlusPlus11);
428 if (LHS.isInvalid())
429 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000430
Richard Smith5b555da2014-11-20 01:24:12 +0000431 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
432 getLangOpts().CPlusPlus11)
433 : ExprResult();
434 if (RHS.isInvalid())
435 return StmtError();
436
437 CaseStmt *CS = new (Context)
438 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000439 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000440 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000441}
442
Chris Lattner34a22092009-03-04 04:23:07 +0000443/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000444void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000445 DiagnoseUnusedExprResult(SubStmt);
446
Chris Lattner34a22092009-03-04 04:23:07 +0000447 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000448 CS->setSubStmt(SubStmt);
449}
450
John McCalldadc5752010-08-24 06:29:42 +0000451StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000452Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000453 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000454 DiagnoseUnusedExprResult(SubStmt);
455
John McCallaab3e412010-08-25 08:40:02 +0000456 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000457 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000458 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000459 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000460
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000461 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000462 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000463 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000464}
465
John McCalldadc5752010-08-24 06:29:42 +0000466StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000467Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
468 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000469 // If the label was multiply defined, reject it now.
470 if (TheDecl->getStmt()) {
471 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
472 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000473 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000474 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000475
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000476 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000477 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
478 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000479 if (!TheDecl->isGnuLocal()) {
480 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000481 if (!TheDecl->isMSAsmLabel()) {
482 // Don't update the location of MS ASM labels. These will result in
483 // a diagnostic, and changing the location here will mess that up.
484 TheDecl->setLocation(IdentLoc);
485 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000486 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000487 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000488}
489
Richard Smithc202b282012-04-14 00:33:13 +0000490StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000491 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000492 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000493 // Fill in the declaration and return it.
494 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000495 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000496}
497
Richard Trieufaca2d82016-02-18 23:58:40 +0000498namespace {
499class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
500 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
501 Sema &SemaRef;
502public:
503 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
504 void VisitBinaryOperator(BinaryOperator *E) {
505 if (E->getOpcode() == BO_Comma)
506 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
507 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
508 }
509};
510}
511
John McCalldadc5752010-08-24 06:29:42 +0000512StmtResult
Richard Smithc7a05a92016-06-29 21:17:59 +0000513Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
514 ConditionResult Cond,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000515 Stmt *thenStmt, SourceLocation ElseLoc,
516 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000517 if (Cond.isInvalid())
518 Cond = ConditionResult(
519 *this, nullptr,
520 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
521 Context.BoolTy, VK_RValue),
522 IfLoc),
523 false);
Anders Carlssondb83d772007-10-10 20:50:11 +0000524
Richard Smithb130fe72016-06-23 19:16:49 +0000525 Expr *CondExpr = Cond.get().second;
Richard Smith03a4aa32016-06-23 19:02:52 +0000526 if (!Diags.isIgnored(diag::warn_comma_operator,
Richard Smithb130fe72016-06-23 19:16:49 +0000527 CondExpr->getExprLoc()))
528 CommaVisitor(*this).Visit(CondExpr);
529
530 if (!elseStmt)
531 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
532 diag::warn_empty_if_body);
533
Richard Smitha547eb22016-07-14 00:11:03 +0000534 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
535 elseStmt);
Richard Smithb130fe72016-06-23 19:16:49 +0000536}
537
538StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Richard Smitha547eb22016-07-14 00:11:03 +0000539 Stmt *InitStmt, ConditionResult Cond,
540 Stmt *thenStmt, SourceLocation ElseLoc,
541 Stmt *elseStmt) {
Richard Smithb130fe72016-06-23 19:16:49 +0000542 if (Cond.isInvalid())
543 return StmtError();
544
Erik Pilkington5cd57172016-08-16 17:44:11 +0000545 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
Richard Smithb130fe72016-06-23 19:16:49 +0000546 getCurFunction()->setHasBranchProtectedScope();
Richard Smith03a4aa32016-06-23 19:02:52 +0000547
548 DiagnoseUnusedExprResult(thenStmt);
Richard Smith03a4aa32016-06-23 19:02:52 +0000549 DiagnoseUnusedExprResult(elseStmt);
550
Richard Smitha547eb22016-07-14 00:11:03 +0000551 return new (Context)
552 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
553 Cond.get().second, thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000554}
Steve Naroff86272ea2007-05-29 02:14:17 +0000555
Chris Lattner67998452007-08-23 18:29:20 +0000556namespace {
557 struct CaseCompareFunctor {
558 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
559 const llvm::APSInt &RHS) {
560 return LHS.first < RHS;
561 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000562 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
563 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
564 return LHS.first < RHS.first;
565 }
Chris Lattner67998452007-08-23 18:29:20 +0000566 bool operator()(const llvm::APSInt &LHS,
567 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
568 return LHS < RHS.first;
569 }
570 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000571}
Chris Lattner67998452007-08-23 18:29:20 +0000572
Chris Lattner4b2ff022007-09-21 18:15:22 +0000573/// CmpCaseVals - Comparison predicate for sorting case values.
574///
575static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
576 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
577 if (lhs.first < rhs.first)
578 return true;
579
580 if (lhs.first == rhs.first &&
581 lhs.second->getCaseLoc().getRawEncoding()
582 < rhs.second->getCaseLoc().getRawEncoding())
583 return true;
584 return false;
585}
586
Douglas Gregorbd6839732010-02-08 22:24:16 +0000587/// CmpEnumVals - Comparison predicate for sorting enumeration values.
588///
589static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
590 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
591{
592 return lhs.first < rhs.first;
593}
594
595/// EqEnumVals - Comparison preficate for uniqing enumeration values.
596///
597static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
598 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
599{
600 return lhs.first == rhs.first;
601}
602
Chris Lattnera96d4272009-10-16 16:45:22 +0000603/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
604/// potentially integral-promoted expression @p expr.
Gabor Horvath64c32412017-08-09 08:57:09 +0000605static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
606 if (const auto *CleanUps = dyn_cast<ExprWithCleanups>(E))
607 E = CleanUps->getSubExpr();
608 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
609 if (ImpCast->getCastKind() != CK_IntegralCast) break;
610 E = ImpCast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000611 }
Gabor Horvath64c32412017-08-09 08:57:09 +0000612 return E->getType();
Chris Lattnera96d4272009-10-16 16:45:22 +0000613}
614
Richard Smith03a4aa32016-06-23 19:02:52 +0000615ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
Douglas Gregore2b37442012-05-04 22:38:52 +0000616 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
617 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000618
Douglas Gregore2b37442012-05-04 22:38:52 +0000619 public:
620 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000621 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
622 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000623
Craig Toppere14c0f82014-03-12 04:55:44 +0000624 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
625 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000626 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
627 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000628
Craig Toppere14c0f82014-03-12 04:55:44 +0000629 SemaDiagnosticBuilder diagnoseIncomplete(
630 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000631 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
632 << T << Cond->getSourceRange();
633 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000634
Craig Toppere14c0f82014-03-12 04:55:44 +0000635 SemaDiagnosticBuilder diagnoseExplicitConv(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000637 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
638 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000639
Craig Toppere14c0f82014-03-12 04:55:44 +0000640 SemaDiagnosticBuilder noteExplicitConv(
641 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000642 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
643 << ConvTy->isEnumeralType() << ConvTy;
644 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000645
Craig Toppere14c0f82014-03-12 04:55:44 +0000646 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
647 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000648 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
649 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000650
Craig Toppere14c0f82014-03-12 04:55:44 +0000651 SemaDiagnosticBuilder noteAmbiguous(
652 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000653 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
654 << ConvTy->isEnumeralType() << ConvTy;
655 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000656
Craig Toppere14c0f82014-03-12 04:55:44 +0000657 SemaDiagnosticBuilder diagnoseConversion(
658 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000659 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000660 }
661 } SwitchDiagnoser(Cond);
662
Richard Smith03a4aa32016-06-23 19:02:52 +0000663 ExprResult CondResult =
Richard Smithccc11812013-05-21 19:05:48 +0000664 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
Richard Smith03a4aa32016-06-23 19:02:52 +0000665 if (CondResult.isInvalid())
666 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667
John McCall5939b162011-08-06 07:30:58 +0000668 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
Richard Smith03a4aa32016-06-23 19:02:52 +0000669 return UsualUnaryConversions(CondResult.get());
670}
John McCall5939b162011-08-06 07:30:58 +0000671
Richard Smithc7a05a92016-06-29 21:17:59 +0000672StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
673 Stmt *InitStmt, ConditionResult Cond) {
Richard Smith03a4aa32016-06-23 19:02:52 +0000674 if (Cond.isInvalid())
Meador Ingef0af05c2015-06-25 22:06:40 +0000675 return StmtError();
John McCalla95172b2010-08-01 00:26:45 +0000676
John McCallaab3e412010-08-25 08:40:02 +0000677 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000678
Richard Smitha547eb22016-07-14 00:11:03 +0000679 SwitchStmt *SS = new (Context)
680 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
John McCallaab3e412010-08-25 08:40:02 +0000681 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000682 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000683}
684
Gabor Greif16e02862010-10-01 22:05:14 +0000685static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000686 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000687 Val.setIsSigned(IsSigned);
688}
689
Richard Smith077d0832014-08-04 00:40:48 +0000690/// Check the specified case value is in range for the given unpromoted switch
691/// type.
692static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
693 unsigned UnpromotedWidth, bool UnpromotedSign) {
694 // If the case value was signed and negative and the switch expression is
695 // unsigned, don't bother to warn: this is implementation-defined behavior.
696 // FIXME: Introduce a second, default-ignored warning for this case?
697 if (UnpromotedWidth < Val.getBitWidth()) {
698 llvm::APSInt ConvVal(Val);
699 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
700 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
701 // FIXME: Use different diagnostics for overflow in conversion to promoted
702 // type versus "switch expression cannot have this value". Use proper
703 // IntRange checking rather than just looking at the unpromoted type here.
704 if (ConvVal != Val)
705 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
706 << ConvVal.toString(10);
707 }
708}
709
Alexis Hunt724f14e2014-11-28 00:53:20 +0000710typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
711
Dmitri Gribenko58683752013-12-05 22:52:07 +0000712/// Returns true if we should emit a diagnostic about this case expression not
713/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000714static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000715 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000716 const Expr *CaseExpr,
717 EnumValsTy::iterator &EI,
718 EnumValsTy::iterator &EIEnd,
719 const llvm::APSInt &Val) {
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000720 if (!ED->isClosed())
721 return false;
722
Alexis Hunt724f14e2014-11-28 00:53:20 +0000723 if (const DeclRefExpr *DRE =
724 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000725 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000726 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000727 QualType EnumType = S.Context.getTypeDeclType(ED);
728 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
729 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000730 return false;
731 }
732 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000733
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000734 if (ED->hasAttr<FlagEnumAttr>())
Alexis Hunt724f14e2014-11-28 00:53:20 +0000735 return !S.IsValueInFlagEnum(ED, Val, false);
Alexis Hunt724f14e2014-11-28 00:53:20 +0000736
Akira Hatanaka3c268af2017-03-21 02:23:00 +0000737 while (EI != EIEnd && EI->first < Val)
738 EI++;
739
740 if (EI != EIEnd && EI->first == Val)
741 return false;
Alexis Hunt724f14e2014-11-28 00:53:20 +0000742
Dmitri Gribenko58683752013-12-05 22:52:07 +0000743 return true;
744}
745
Gabor Horvath64c32412017-08-09 08:57:09 +0000746static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
747 const Expr *Case) {
748 QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
749 QualType CaseType = Case->getType();
750
751 const EnumType *CondEnumType = CondType->getAs<EnumType>();
752 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
753 if (!CondEnumType || !CaseEnumType)
754 return;
755
Gabor Horvathb57e2642017-08-09 12:34:58 +0000756 // Ignore anonymous enums.
757 if (!CondEnumType->getDecl()->getIdentifier())
758 return;
759 if (!CaseEnumType->getDecl()->getIdentifier())
760 return;
761
Gabor Horvath64c32412017-08-09 08:57:09 +0000762 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
763 return;
764
Gabor Horvath0284a202017-08-09 20:56:43 +0000765 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
Gabor Horvath64c32412017-08-09 08:57:09 +0000766 << CondType << CaseType << Cond->getSourceRange()
767 << Case->getSourceRange();
768}
769
John McCalldadc5752010-08-24 06:29:42 +0000770StmtResult
John McCallb268a282010-08-23 23:25:46 +0000771Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
772 Stmt *BodyStmt) {
773 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000774 assert(SS == getCurFunction()->SwitchStack.back() &&
775 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000776
David Majnemer418ad3f2014-12-15 07:46:12 +0000777 getCurFunction()->SwitchStack.pop_back();
778
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000779 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000780 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000781
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000782 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000783 if (!CondExpr) return StmtError();
784
785 QualType CondType = CondExpr->getType();
786
Gabor Horvath64c32412017-08-09 08:57:09 +0000787 const Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000788 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000789 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000790
Chris Lattnera96d4272009-10-16 16:45:22 +0000791 // C++ 6.4.2.p2:
792 // Integral promotions are performed (on the switch condition).
793 //
794 // A case value unrepresentable by the original switch condition
795 // type (before the promotion) doesn't make sense, even when it can
796 // be represented by the promoted type. Therefore we need to find
797 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000798 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000799 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000801 // appropriate type now, just return an error.
802 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000803 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000804
Chris Lattner4ebae652010-04-16 23:34:13 +0000805 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000806 // switch(bool_expr) {...} is often a programmer error, e.g.
807 // switch(n && mask) { ... } // Doh - should be "n & mask".
808 // One can always use an if statement instead of switch(bool_expr).
809 Diag(SwitchLoc, diag::warn_bool_switch_condition)
810 << CondExpr->getSourceRange();
811 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000812 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000813
Richard Smith077d0832014-08-04 00:40:48 +0000814 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000815 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000816 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000817 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000818 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
819 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
820
821 // Get the width and signedness that the condition might actually have, for
822 // warning purposes.
823 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
824 // type.
825 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000826 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000827 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000828 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000830 // Accumulate all of the case values in a vector so that we can sort them
831 // and detect duplicates. This vector contains the APInt for the case after
832 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000833 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000834 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000836 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000837 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
838 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000839
Craig Topperc3ec1492014-05-26 06:22:03 +0000840 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000841
Chris Lattner10cb5e52007-08-23 06:23:56 +0000842 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000844 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000845 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000846
Anders Carlsson51873c22007-07-22 07:07:56 +0000847 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000848 if (TheDefaultStmt) {
849 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000850 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000851
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000852 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000853 // we'll return a valid AST. This requires recursing down the AST and
854 // finding it, not something we are set up to do right now. For now,
855 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000856 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000857 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000858 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000860 } else {
861 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattnera65e1f32008-01-16 19:17:22 +0000863 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000864
865 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
866 HasDependentValue = true;
867 break;
868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Gabor Horvath64c32412017-08-09 08:57:09 +0000870 checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
871
Richard Smithf8379a02012-01-18 23:55:52 +0000872 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000874 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000875 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
876 // constant expression of the promoted type of the switch condition.
877 ExprResult ConvLo =
878 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
879 if (ConvLo.isInvalid()) {
880 CaseListIsErroneous = true;
881 continue;
882 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000883 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000884 } else {
885 // We already verified that the expression has a i-c-e value (C99
886 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000887 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000888
889 // If the LHS is not the same type as the condition, insert an implicit
890 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000891 Lo = DefaultLvalueConversion(Lo).get();
892 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000893 }
894
Richard Smith077d0832014-08-04 00:40:48 +0000895 // Check the unconverted value is within the range of possible values of
896 // the switch expression.
897 checkCaseValue(*this, Lo->getLocStart(), LoVal,
898 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
899
900 // Convert the value to the same width/sign as the condition.
901 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000902
Chris Lattnera65e1f32008-01-16 19:17:22 +0000903 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000904
Chris Lattner10cb5e52007-08-23 06:23:56 +0000905 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000906 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000907 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000908 CS->getRHS()->isValueDependent()) {
909 HasDependentValue = true;
910 break;
911 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000912 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000913 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000914 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000915 }
916 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000917
918 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000919 // If we don't have a default statement, check whether the
920 // condition is constant.
921 llvm::APSInt ConstantCondValue;
922 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000923 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000924 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
925 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000926 assert(!HasConstantCond ||
927 (ConstantCondValue.getBitWidth() == CondWidth &&
928 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000929 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000930 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000931
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000932 // Sort all the scalar case values so we can easily detect duplicates.
933 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
934
935 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000936 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
937 if (ShouldCheckConstantCond &&
938 CaseVals[i].first == ConstantCondValue)
939 ShouldCheckConstantCond = false;
940
941 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000942 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000943 // First, determine if either case value has a name
944 StringRef PrevString, CurrString;
945 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
946 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
947 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
948 PrevString = DeclRef->getDecl()->getName();
949 }
950 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
951 CurrString = DeclRef->getDecl()->getName();
952 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000953 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000954 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000955
956 if (PrevString == CurrString)
957 Diag(CaseVals[i].second->getLHS()->getLocStart(),
958 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000959 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000960 else
961 Diag(CaseVals[i].second->getLHS()->getLocStart(),
962 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000963 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
964 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000965 CaseValStr;
966
John McCalld3dfbd62010-05-18 03:19:21 +0000967 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000968 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000969 // FIXME: We really want to remove the bogus case stmt from the
970 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000971 CaseListIsErroneous = true;
972 }
973 }
974 }
Mike Stump11289f42009-09-09 15:08:12 +0000975
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 // Detect duplicate case ranges, which usually don't exist at all in
977 // the first place.
978 if (!CaseRanges.empty()) {
979 // Sort all the case ranges by their low value so we can easily detect
980 // overlaps between ranges.
981 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000982
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000983 // Scan the ranges, computing the high values and removing empty ranges.
984 std::vector<llvm::APSInt> HiVals;
985 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000986 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000987 CaseStmt *CR = CaseRanges[i].second;
988 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000989 llvm::APSInt HiVal;
990
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000991 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000992 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
993 // constant expression of the promoted type of the switch condition.
994 ExprResult ConvHi =
995 CheckConvertedConstantExpression(Hi, CondType, HiVal,
996 CCEK_CaseValue);
997 if (ConvHi.isInvalid()) {
998 CaseListIsErroneous = true;
999 continue;
1000 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001001 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +00001002 } else {
1003 HiVal = Hi->EvaluateKnownConstInt(Context);
1004
1005 // If the RHS is not the same type as the condition, insert an
1006 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001007 Hi = DefaultLvalueConversion(Hi).get();
1008 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +00001009 }
Mike Stump11289f42009-09-09 15:08:12 +00001010
Richard Smith077d0832014-08-04 00:40:48 +00001011 // Check the unconverted value is within the range of possible values of
1012 // the switch expression.
1013 checkCaseValue(*this, Hi->getLocStart(), HiVal,
1014 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1015
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001016 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +00001017 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001019 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001021 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +00001022 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001023 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
1024 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +00001025 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001026 CaseRanges.erase(CaseRanges.begin()+i);
Richard Trieucc3949d2016-02-18 22:34:54 +00001027 --i;
1028 --e;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 continue;
1030 }
John McCalld3dfbd62010-05-18 03:19:21 +00001031
1032 if (ShouldCheckConstantCond &&
1033 LoVal <= ConstantCondValue &&
1034 ConstantCondValue <= HiVal)
1035 ShouldCheckConstantCond = false;
1036
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 HiVals.push_back(HiVal);
1038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001040 // Rescan the ranges, looking for overlap with singleton values and other
1041 // ranges. Since the range list is sorted, we only need to compare case
1042 // ranges with their neighbors.
1043 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1044 llvm::APSInt &CRLo = CaseRanges[i].first;
1045 llvm::APSInt &CRHi = HiVals[i];
1046 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001048 // Check to see whether the case range overlaps with any
1049 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001050 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001051 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001053 // Find the smallest value >= the lower bound. If I is in the
1054 // case range, then we have overlap.
1055 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1056 CaseVals.end(), CRLo,
1057 CaseCompareFunctor());
1058 if (I != CaseVals.end() && I->first < CRHi) {
1059 OverlapVal = I->first; // Found overlap with scalar.
1060 OverlapStmt = I->second;
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001063 // Find the smallest value bigger than the upper bound.
1064 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1065 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1066 OverlapVal = (I-1)->first; // Found overlap with scalar.
1067 OverlapStmt = (I-1)->second;
1068 }
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001070 // Check to see if this case stmt overlaps with the subsequent
1071 // case range.
1072 if (i && CRLo <= HiVals[i-1]) {
1073 OverlapVal = HiVals[i-1]; // Found overlap with range.
1074 OverlapStmt = CaseRanges[i-1].second;
1075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001077 if (OverlapStmt) {
1078 // If we have a duplicate, report it.
1079 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1080 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001081 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001082 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001083 // FIXME: We really want to remove the bogus case stmt from the
1084 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001085 CaseListIsErroneous = true;
1086 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001087 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001088 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001089
John McCalld3dfbd62010-05-18 03:19:21 +00001090 // Complain if we have a constant condition and we didn't find a match.
1091 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1092 // TODO: it would be nice if we printed enums as enums, chars as
1093 // chars, etc.
1094 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1095 << ConstantCondValue.toString(10)
1096 << CondExpr->getSourceRange();
1097 }
1098
1099 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001100 // values. We only issue a warning if there is not 'default:', but
1101 // we still do the analysis to preserve this information in the AST
1102 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001103 //
Chris Lattner51679082010-09-16 17:09:42 +00001104 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001105
Douglas Gregorbd6839732010-02-08 22:24:16 +00001106 // If switch has default case, then ignore it.
Alex Lorenz660195f2016-12-08 14:46:05 +00001107 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1108 ET->getDecl()->isCompleteDefinition()) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001109 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001110 EnumValsTy EnumVals;
1111
John McCalld3dfbd62010-05-18 03:19:21 +00001112 // Gather all enum values, set their type and sort them,
1113 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001114 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001115 llvm::APSInt Val = EDI->getInitVal();
1116 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001117 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001118 }
1119 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001120 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001121 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001122
1123 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001124 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001125 CI != CaseVals.end(); CI++) {
1126 Expr *CaseExpr = CI->second->getLHS();
1127 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1128 CI->first))
1129 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1130 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001131 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001132
David Blaikiee476f972012-01-22 02:31:55 +00001133 // See which of case ranges aren't in enum
1134 EI = EnumVals.begin();
1135 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001136 RI != CaseRanges.end(); RI++) {
1137 Expr *CaseExpr = RI->second->getLHS();
1138 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1139 RI->first))
1140 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1141 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001142
Chad Rosier02a84392012-08-10 17:56:09 +00001143 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001144 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1145 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001146
1147 CaseExpr = RI->second->getRHS();
1148 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1149 Hi))
1150 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1151 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001153
Ted Kremenekc42f3452010-09-09 00:05:53 +00001154 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001155 auto CI = CaseVals.begin();
1156 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001157 bool hasCasesNotInSwitch = false;
1158
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001159 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001160
Alexis Hunt724f14e2014-11-28 00:53:20 +00001161 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001162 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001163 while (CI != CaseVals.end() && CI->first < EI->first)
1164 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Douglas Gregorbd6839732010-02-08 22:24:16 +00001166 if (CI != CaseVals.end() && CI->first == EI->first)
1167 continue;
1168
Ted Kremenekc42f3452010-09-09 00:05:53 +00001169 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001170 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001171 llvm::APSInt Hi =
1172 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001173 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001174 if (EI->first <= Hi)
1175 break;
1176 }
1177
Ted Kremenekc42f3452010-09-09 00:05:53 +00001178 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001179 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001180 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001181 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001184 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
David Blaikie60ac6382012-01-23 04:46:12 +00001185 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001186
Chris Lattner51679082010-09-16 17:09:42 +00001187 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001188 if (!UnhandledNames.empty()) {
1189 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1190 TheDefaultStmt ? diag::warn_def_missing_case
1191 : diag::warn_missing_case)
1192 << (int)UnhandledNames.size();
1193
1194 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1195 I != E; ++I)
1196 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001197 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001198
1199 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001200 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001201 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001202 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001203
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001204 if (BodyStmt)
1205 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1206 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001207
Mike Stump87c57ac2009-05-16 07:39:55 +00001208 // FIXME: If the case list was broken is some way, we don't have a good system
1209 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001210 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001211 return StmtError();
1212
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001213 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001214}
1215
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001216void
1217Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1218 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001219 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001220 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001221
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001222 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001223 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001224 SrcType->isIntegerType()) {
1225 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1226 SrcExpr->isIntegerConstantExpr(Context)) {
1227 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001228 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001229 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1230
1231 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001232 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001233 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001234
Akira Hatanaka3c268af2017-03-21 02:23:00 +00001235 if (!ED->isClosed())
1236 return;
1237
Alexis Hunt724f14e2014-11-28 00:53:20 +00001238 if (ED->hasAttr<FlagEnumAttr>()) {
1239 if (!IsValueInFlagEnum(ED, RhsVal, true))
1240 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001241 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001242 } else {
1243 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1244 EnumValsTy;
1245 EnumValsTy EnumVals;
1246
1247 // Gather all enum values, set their type and sort them,
1248 // allowing easier comparison with rhs constant.
1249 for (auto *EDI : ED->enumerators()) {
1250 llvm::APSInt Val = EDI->getInitVal();
1251 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1252 EnumVals.push_back(std::make_pair(Val, EDI));
1253 }
1254 if (EnumVals.empty())
1255 return;
1256 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1257 EnumValsTy::iterator EIend =
1258 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1259
1260 // See which values aren't in the enum.
1261 EnumValsTy::const_iterator EI = EnumVals.begin();
1262 while (EI != EIend && EI->first < RhsVal)
1263 EI++;
1264 if (EI == EIend || EI->first != RhsVal) {
1265 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1266 << DstType.getUnqualifiedType();
1267 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001268 }
1269 }
1270 }
1271}
1272
Richard Smith03a4aa32016-06-23 19:02:52 +00001273StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1274 Stmt *Body) {
1275 if (Cond.isInvalid())
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001276 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001277
Richard Smith03a4aa32016-06-23 19:02:52 +00001278 auto CondVal = Cond.get();
1279 CheckBreakContinueBinding(CondVal.second);
1280
1281 if (CondVal.second &&
1282 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1283 CommaVisitor(*this).Visit(CondVal.second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001284
John McCallb268a282010-08-23 23:25:46 +00001285 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001286
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001287 if (isa<NullStmt>(Body))
1288 getCurCompoundScope().setHasEmptyLoopBodies();
1289
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001290 return new (Context)
Richard Smith03a4aa32016-06-23 19:02:52 +00001291 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001292}
1293
John McCalldadc5752010-08-24 06:29:42 +00001294StmtResult
John McCallb268a282010-08-23 23:25:46 +00001295Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001296 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001297 Expr *Cond, SourceLocation CondRParen) {
1298 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001299
Serge Pavlov09f99242014-01-23 15:05:00 +00001300 CheckBreakContinueBinding(Cond);
Richard Smith03a4aa32016-06-23 19:02:52 +00001301 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001302 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001303 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001304 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001305
Richard Smith945f8d32013-01-14 22:39:08 +00001306 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001307 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001308 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001309 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310
John McCallb268a282010-08-23 23:25:46 +00001311 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001312
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001313 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001314}
1315
Richard Trieu451a5db2012-04-30 18:01:30 +00001316namespace {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001317 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1318 using DeclSetVector =
1319 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1320 llvm::SmallPtrSet<VarDecl *, 8>>;
1321
Richard Trieu451a5db2012-04-30 18:01:30 +00001322 // This visitor will traverse a conditional statement and store all
1323 // the evaluated decls into a vector. Simple is set to true if none
1324 // of the excluded constructs are used.
1325 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001326 DeclSetVector &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001327 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001328 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001329 public:
1330 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001331
Richard Trieu5fb874a2017-06-02 04:24:46 +00001332 DeclExtractor(Sema &S, DeclSetVector &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001333 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001334 Inherited(S.Context),
1335 Decls(Decls),
1336 Ranges(Ranges),
1337 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001338
Richard Trieu9d228802013-05-31 22:46:45 +00001339 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001340
Richard Trieu9d228802013-05-31 22:46:45 +00001341 // Replaces the method in EvaluatedExprVisitor.
1342 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001343 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001344 }
1345
1346 // Any Stmt not whitelisted will cause the condition to be marked complex.
1347 void VisitStmt(Stmt *S) {
1348 Simple = false;
1349 }
1350
1351 void VisitBinaryOperator(BinaryOperator *E) {
1352 Visit(E->getLHS());
1353 Visit(E->getRHS());
1354 }
1355
1356 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001357 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001358 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001359
Richard Trieu9d228802013-05-31 22:46:45 +00001360 void VisitUnaryOperator(UnaryOperator *E) {
1361 // Skip checking conditionals with derefernces.
1362 if (E->getOpcode() == UO_Deref)
1363 Simple = false;
1364 else
1365 Visit(E->getSubExpr());
1366 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001367
Richard Trieu9d228802013-05-31 22:46:45 +00001368 void VisitConditionalOperator(ConditionalOperator *E) {
1369 Visit(E->getCond());
1370 Visit(E->getTrueExpr());
1371 Visit(E->getFalseExpr());
1372 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 void VisitParenExpr(ParenExpr *E) {
1375 Visit(E->getSubExpr());
1376 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1379 Visit(E->getOpaqueValue()->getSourceExpr());
1380 Visit(E->getFalseExpr());
1381 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001382
Richard Trieu9d228802013-05-31 22:46:45 +00001383 void VisitIntegerLiteral(IntegerLiteral *E) { }
1384 void VisitFloatingLiteral(FloatingLiteral *E) { }
1385 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1386 void VisitCharacterLiteral(CharacterLiteral *E) { }
1387 void VisitGNUNullExpr(GNUNullExpr *E) { }
1388 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001389
Richard Trieu9d228802013-05-31 22:46:45 +00001390 void VisitDeclRefExpr(DeclRefExpr *E) {
1391 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1392 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001393
Richard Trieu9d228802013-05-31 22:46:45 +00001394 Ranges.push_back(E->getSourceRange());
1395
1396 Decls.insert(VD);
1397 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001398
1399 }; // end class DeclExtractor
1400
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001401 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001402 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001403 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Richard Trieu5fb874a2017-06-02 04:24:46 +00001404 DeclSetVector &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001405 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001406
Richard Trieu9d228802013-05-31 22:46:45 +00001407 public:
1408 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001409
Richard Trieu5fb874a2017-06-02 04:24:46 +00001410 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
Richard Trieu9d228802013-05-31 22:46:45 +00001411 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1412 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001413
Richard Trieu9d228802013-05-31 22:46:45 +00001414 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001415 }
1416
Richard Trieu9d228802013-05-31 22:46:45 +00001417 void VisitReturnStmt(ReturnStmt *S) {
1418 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001419 }
1420
Richard Trieu9d228802013-05-31 22:46:45 +00001421 void VisitBreakStmt(BreakStmt *S) {
1422 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001423 }
1424
Richard Trieu9d228802013-05-31 22:46:45 +00001425 void VisitGotoStmt(GotoStmt *S) {
1426 FoundDecl = true;
1427 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001428
Richard Trieu9d228802013-05-31 22:46:45 +00001429 void VisitCastExpr(CastExpr *E) {
1430 if (E->getCastKind() == CK_LValueToRValue)
1431 CheckLValueToRValueCast(E->getSubExpr());
1432 else
1433 Visit(E->getSubExpr());
1434 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001435
Richard Trieu9d228802013-05-31 22:46:45 +00001436 void CheckLValueToRValueCast(Expr *E) {
1437 E = E->IgnoreParenImpCasts();
1438
1439 if (isa<DeclRefExpr>(E)) {
1440 return;
1441 }
1442
1443 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1444 Visit(CO->getCond());
1445 CheckLValueToRValueCast(CO->getTrueExpr());
1446 CheckLValueToRValueCast(CO->getFalseExpr());
1447 return;
1448 }
1449
1450 if (BinaryConditionalOperator *BCO =
1451 dyn_cast<BinaryConditionalOperator>(E)) {
1452 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1453 CheckLValueToRValueCast(BCO->getFalseExpr());
1454 return;
1455 }
1456
1457 Visit(E);
1458 }
1459
1460 void VisitDeclRefExpr(DeclRefExpr *E) {
1461 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1462 if (Decls.count(VD))
1463 FoundDecl = true;
1464 }
1465
Steven Wu92910f62016-03-10 02:02:48 +00001466 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1467 // Only need to visit the semantics for POE.
1468 // SyntaticForm doesn't really use the Decal.
1469 for (auto *S : POE->semantics()) {
1470 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1471 // Look past the OVE into the expression it binds.
1472 Visit(OVE->getSourceExpr());
1473 else
1474 Visit(S);
1475 }
1476 }
1477
Richard Trieu9d228802013-05-31 22:46:45 +00001478 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001479
1480 }; // end class DeclMatcher
1481
1482 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1483 Expr *Third, Stmt *Body) {
1484 // Condition is empty
1485 if (!Second) return;
1486
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001487 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1488 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001489 return;
1490
1491 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
Richard Trieu5fb874a2017-06-02 04:24:46 +00001492 DeclSetVector Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001493 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001494 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001495 DE.Visit(Second);
1496
1497 // Don't analyze complex conditionals.
1498 if (!DE.isSimple()) return;
1499
1500 // No decls found.
1501 if (Decls.size() == 0) return;
1502
Richard Trieu0030f1d2012-05-04 03:01:54 +00001503 // Don't warn on volatile, static, or global variables.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001504 for (auto *VD : Decls)
1505 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1506 return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001507
1508 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1509 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1510 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1511 return;
1512
1513 // Load decl names into diagnostic.
Richard Trieu5fb874a2017-06-02 04:24:46 +00001514 if (Decls.size() > 4) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001515 PDiag << 0;
Richard Trieu5fb874a2017-06-02 04:24:46 +00001516 } else {
1517 PDiag << (unsigned)Decls.size();
1518 for (auto *VD : Decls)
1519 PDiag << VD->getDeclName();
Richard Trieu451a5db2012-04-30 18:01:30 +00001520 }
1521
Richard Trieu5fb874a2017-06-02 04:24:46 +00001522 for (auto Range : Ranges)
1523 PDiag << Range;
Richard Trieu451a5db2012-04-30 18:01:30 +00001524
1525 S.Diag(Ranges.begin()->getBegin(), PDiag);
1526 }
1527
Richard Trieu4e7c9622013-08-06 21:31:54 +00001528 // If Statement is an incemement or decrement, return true and sets the
1529 // variables Increment and DRE.
1530 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1531 DeclRefExpr *&DRE) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001532 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1533 if (!Cleanups->cleanupsHaveSideEffects())
1534 Statement = Cleanups->getSubExpr();
1535
Richard Trieu4e7c9622013-08-06 21:31:54 +00001536 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1537 switch (UO->getOpcode()) {
1538 default: return false;
1539 case UO_PostInc:
1540 case UO_PreInc:
1541 Increment = true;
1542 break;
1543 case UO_PostDec:
1544 case UO_PreDec:
1545 Increment = false;
1546 break;
1547 }
1548 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1549 return DRE;
1550 }
1551
1552 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1553 FunctionDecl *FD = Call->getDirectCallee();
1554 if (!FD || !FD->isOverloadedOperator()) return false;
1555 switch (FD->getOverloadedOperator()) {
1556 default: return false;
1557 case OO_PlusPlus:
1558 Increment = true;
1559 break;
1560 case OO_MinusMinus:
1561 Increment = false;
1562 break;
1563 }
1564 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1565 return DRE;
1566 }
1567
1568 return false;
1569 }
1570
Serge Pavlov09f99242014-01-23 15:05:00 +00001571 // A visitor to determine if a continue or break statement is a
1572 // subexpression.
Eli Friedmane91b2e62017-07-04 00:52:24 +00001573 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
Serge Pavlov09f99242014-01-23 15:05:00 +00001574 SourceLocation BreakLoc;
1575 SourceLocation ContinueLoc;
Eli Friedmane91b2e62017-07-04 00:52:24 +00001576 bool InSwitch = false;
1577
Richard Trieu4e7c9622013-08-06 21:31:54 +00001578 public:
Eli Friedmane91b2e62017-07-04 00:52:24 +00001579 BreakContinueFinder(Sema &S, const Stmt* Body) :
Serge Pavlov09f99242014-01-23 15:05:00 +00001580 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001581 Visit(Body);
1582 }
1583
Eli Friedmane91b2e62017-07-04 00:52:24 +00001584 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001585
Eli Friedmane91b2e62017-07-04 00:52:24 +00001586 void VisitContinueStmt(const ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001587 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001588 }
1589
Eli Friedmane91b2e62017-07-04 00:52:24 +00001590 void VisitBreakStmt(const BreakStmt* E) {
1591 if (!InSwitch)
1592 BreakLoc = E->getBreakLoc();
1593 }
1594
1595 void VisitSwitchStmt(const SwitchStmt* S) {
1596 if (const Stmt *Init = S->getInit())
1597 Visit(Init);
1598 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1599 Visit(CondVar);
1600 if (const Stmt *Cond = S->getCond())
1601 Visit(Cond);
1602
1603 // Don't return break statements from the body of a switch.
1604 InSwitch = true;
1605 if (const Stmt *Body = S->getBody())
1606 Visit(Body);
1607 InSwitch = false;
1608 }
1609
1610 void VisitForStmt(const ForStmt *S) {
1611 // Only visit the init statement of a for loop; the body
1612 // has a different break/continue scope.
1613 if (const Stmt *Init = S->getInit())
1614 Visit(Init);
1615 }
1616
1617 void VisitWhileStmt(const WhileStmt *) {
1618 // Do nothing; the children of a while loop have a different
1619 // break/continue scope.
1620 }
1621
1622 void VisitDoStmt(const DoStmt *) {
1623 // Do nothing; the children of a while loop have a different
1624 // break/continue scope.
1625 }
1626
1627 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1628 // Only visit the initialization of a for loop; the body
1629 // has a different break/continue scope.
1630 if (const Stmt *Range = S->getRangeStmt())
1631 Visit(Range);
1632 if (const Stmt *Begin = S->getBeginStmt())
1633 Visit(Begin);
1634 if (const Stmt *End = S->getEndStmt())
1635 Visit(End);
1636 }
1637
1638 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1639 // Only visit the initialization of a for loop; the body
1640 // has a different break/continue scope.
1641 if (const Stmt *Element = S->getElement())
1642 Visit(Element);
1643 if (const Stmt *Collection = S->getCollection())
1644 Visit(Collection);
Serge Pavlov09f99242014-01-23 15:05:00 +00001645 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001646
Serge Pavlov09f99242014-01-23 15:05:00 +00001647 bool ContinueFound() { return ContinueLoc.isValid(); }
1648 bool BreakFound() { return BreakLoc.isValid(); }
1649 SourceLocation GetContinueLoc() { return ContinueLoc; }
1650 SourceLocation GetBreakLoc() { return BreakLoc; }
1651
1652 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001653
1654 // Emit a warning when a loop increment/decrement appears twice per loop
1655 // iteration. The conditions which trigger this warning are:
1656 // 1) The last statement in the loop body and the third expression in the
1657 // for loop are both increment or both decrement of the same variable
1658 // 2) No continue statements in the loop body.
1659 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1660 // Return when there is nothing to check.
1661 if (!Body || !Third) return;
1662
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001663 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1664 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001665 return;
1666
1667 // Get the last statement from the loop body.
1668 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1669 if (!CS || CS->body_empty()) return;
1670 Stmt *LastStmt = CS->body_back();
1671 if (!LastStmt) return;
1672
1673 bool LoopIncrement, LastIncrement;
1674 DeclRefExpr *LoopDRE, *LastDRE;
1675
1676 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1677 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1678
1679 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001680 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001681 if (LoopIncrement != LastIncrement ||
1682 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1683
Serge Pavlov09f99242014-01-23 15:05:00 +00001684 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001685
1686 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1687 << LastDRE->getDecl() << LastIncrement;
1688 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1689 << LoopIncrement;
1690 }
1691
Richard Trieu451a5db2012-04-30 18:01:30 +00001692} // end namespace
1693
Serge Pavlov09f99242014-01-23 15:05:00 +00001694
1695void Sema::CheckBreakContinueBinding(Expr *E) {
1696 if (!E || getLangOpts().CPlusPlus)
1697 return;
1698 BreakContinueFinder BCFinder(*this, E);
1699 Scope *BreakParent = CurScope->getBreakParent();
1700 if (BCFinder.BreakFound() && BreakParent) {
1701 if (BreakParent->getFlags() & Scope::SwitchScope) {
1702 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1703 } else {
1704 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1705 << "break";
1706 }
1707 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1708 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1709 << "continue";
1710 }
1711}
1712
Richard Smith03a4aa32016-06-23 19:02:52 +00001713StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1714 Stmt *First, ConditionResult Second,
1715 FullExprArg third, SourceLocation RParenLoc,
1716 Stmt *Body) {
1717 if (Second.isInvalid())
1718 return StmtError();
1719
David Blaikiebbafb8a2012-03-11 07:00:24 +00001720 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001721 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001722 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1723 // declare identifiers for objects having storage class 'auto' or
1724 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001725 for (auto *DI : DS->decls()) {
1726 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001727 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001728 VD = nullptr;
1729 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001730 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1731 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001732 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001733 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001734 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001735 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001736
Richard Smith03a4aa32016-06-23 19:02:52 +00001737 CheckBreakContinueBinding(Second.get().second);
Serge Pavlov09f99242014-01-23 15:05:00 +00001738 CheckBreakContinueBinding(third.get());
1739
Richard Smith03a4aa32016-06-23 19:02:52 +00001740 if (!Second.get().first)
1741 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1742 Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001743 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001744
Richard Smith03a4aa32016-06-23 19:02:52 +00001745 if (Second.get().second &&
Richard Trieufaca2d82016-02-18 23:58:40 +00001746 !Diags.isIgnored(diag::warn_comma_operator,
Richard Smith03a4aa32016-06-23 19:02:52 +00001747 Second.get().second->getExprLoc()))
1748 CommaVisitor(*this).Visit(Second.get().second);
Richard Trieufaca2d82016-02-18 23:58:40 +00001749
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001750 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751
Anders Carlsson1682af52009-08-01 01:39:59 +00001752 DiagnoseUnusedExprResult(First);
1753 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001754 DiagnoseUnusedExprResult(Body);
1755
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001756 if (isa<NullStmt>(Body))
1757 getCurCompoundScope().setHasEmptyLoopBodies();
1758
Richard Smith03a4aa32016-06-23 19:02:52 +00001759 return new (Context)
1760 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1761 Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001762}
1763
John McCall34376a62010-12-04 03:47:34 +00001764/// In an Objective C collection iteration statement:
1765/// for (x in y)
1766/// x can be an arbitrary l-value expression. Bind it up as a
1767/// full-expression.
1768StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001769 // Reduce placeholder expressions here. Note that this rejects the
1770 // use of pseudo-object l-values in this position.
1771 ExprResult result = CheckPlaceholderExpr(E);
1772 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001773 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001774
Richard Smith945f8d32013-01-14 22:39:08 +00001775 ExprResult FullExpr = ActOnFinishFullExpr(E);
1776 if (FullExpr.isInvalid())
1777 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001778 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001779}
1780
John McCall53848232011-07-27 01:07:15 +00001781ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001782Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1783 if (!collection)
1784 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001785
Kaelyn Takata15867822014-11-21 18:48:04 +00001786 ExprResult result = CorrectDelayedTyposInExpr(collection);
1787 if (!result.isUsable())
1788 return ExprError();
1789 collection = result.get();
1790
John McCall53848232011-07-27 01:07:15 +00001791 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001792 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001793
1794 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001795 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001796 if (result.isInvalid())
1797 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001798 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001799
1800 // The operand needs to have object-pointer type.
1801 // TODO: should we do a contextual conversion?
1802 const ObjCObjectPointerType *pointerType =
1803 collection->getType()->getAs<ObjCObjectPointerType>();
1804 if (!pointerType)
1805 return Diag(forLoc, diag::err_collection_expr_type)
1806 << collection->getType() << collection->getSourceRange();
1807
1808 // Check that the operand provides
1809 // - countByEnumeratingWithState:objects:count:
1810 const ObjCObjectType *objectType = pointerType->getObjectType();
1811 ObjCInterfaceDecl *iface = objectType->getInterface();
1812
1813 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001814 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001815 if (iface &&
Richard Smithdb0ac552015-12-18 22:40:25 +00001816 (getLangOpts().ObjCAutoRefCount
1817 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1818 diag::err_arc_collection_forward, collection)
1819 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
John McCall53848232011-07-27 01:07:15 +00001820 // Otherwise, if we have any useful type information, check that
1821 // the type declares the appropriate method.
1822 } else if (iface || !objectType->qual_empty()) {
1823 IdentifierInfo *selectorIdents[] = {
1824 &Context.Idents.get("countByEnumeratingWithState"),
1825 &Context.Idents.get("objects"),
1826 &Context.Idents.get("count")
1827 };
1828 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1829
Craig Topperc3ec1492014-05-26 06:22:03 +00001830 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001831
1832 // If there's an interface, look in both the public and private APIs.
1833 if (iface) {
1834 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001835 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001836 }
1837
1838 // Also check protocol qualifiers.
1839 if (!method)
1840 method = LookupMethodInQualifiedType(selector, pointerType,
1841 /*instance*/ true);
1842
1843 // If we didn't find it anywhere, give up.
1844 if (!method) {
1845 Diag(forLoc, diag::warn_collection_expr_type)
1846 << collection->getType() << selector << collection->getSourceRange();
1847 }
1848
1849 // TODO: check for an incompatible signature?
1850 }
1851
1852 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001853 return collection;
John McCall53848232011-07-27 01:07:15 +00001854}
1855
John McCalldadc5752010-08-24 06:29:42 +00001856StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001857Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001858 Stmt *First, Expr *collection,
1859 SourceLocation RParenLoc) {
Akira Hatanaka39013772017-04-19 17:54:08 +00001860 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier02a84392012-08-10 17:56:09 +00001861
1862 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001863 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001864
Fariborz Jahanian93977672008-01-10 20:33:58 +00001865 if (First) {
1866 QualType FirstType;
1867 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001868 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001869 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1870 diag::err_toomany_element_decls));
1871
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001872 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1873 if (!D || D->isInvalidDecl())
1874 return StmtError();
1875
John McCall31168b02011-06-15 23:02:42 +00001876 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001877 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1878 // declare identifiers for objects having storage class 'auto' or
1879 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001880 if (!D->hasLocalStorage())
1881 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001882 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001883
1884 // If the type contained 'auto', deduce the 'auto' to 'id'.
1885 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001886 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1887 VK_RValue);
1888 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001889 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1890 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001891 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001892 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001893 D->setInvalidDecl();
1894 return StmtError();
1895 }
1896
Richard Smith061f1e22013-04-30 21:23:01 +00001897 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001898
Richard Smith51ec0cf2017-02-21 01:17:38 +00001899 if (!inTemplateInstantiation()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001900 SourceLocation Loc =
1901 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001902 Diag(Loc, diag::warn_auto_var_is_id)
1903 << D->getDeclName();
1904 }
1905 }
1906
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001907 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001908 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001909 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001910 return StmtError(Diag(First->getLocStart(),
1911 diag::err_selector_element_not_lvalue)
1912 << First->getSourceRange());
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001915 if (FirstType.isConstQualified())
1916 Diag(ForLoc, diag::err_selector_element_const_type)
1917 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001918 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001919 if (!FirstType->isDependentType() &&
1920 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001921 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001922 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1923 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001924 }
Chad Rosier02a84392012-08-10 17:56:09 +00001925
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001926 if (CollectionExprResult.isInvalid())
1927 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001928
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001929 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001930 if (CollectionExprResult.isInvalid())
1931 return StmtError();
1932
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001933 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1934 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001935}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001936
Richard Smith02e85f32011-04-14 22:09:26 +00001937/// Finish building a variable declaration for a for-range statement.
1938/// \return true if an error occurs.
1939static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001940 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001941 if (Decl->getType()->isUndeducedType()) {
1942 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1943 if (!Res.isUsable()) {
1944 Decl->setInvalidDecl();
1945 return true;
1946 }
1947 Init = Res.get();
1948 }
1949
Richard Smith02e85f32011-04-14 22:09:26 +00001950 // Deduce the type for the iterator variable now rather than leaving it to
1951 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001952 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001953 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001954 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001955 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001956 SemaRef.Diag(Loc, DiagID) << Init->getType();
1957 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001958 Decl->setInvalidDecl();
1959 return true;
1960 }
Richard Smith061f1e22013-04-30 21:23:01 +00001961 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001962
John McCall31168b02011-06-15 23:02:42 +00001963 // In ARC, infer lifetime.
1964 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1965 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001966 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001967 SemaRef.inferObjCARCLifetime(Decl))
1968 Decl->setInvalidDecl();
1969
Richard Smith3beb7c62017-01-12 02:27:38 +00001970 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001971 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001972 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001973 return false;
1974}
1975
Sam Panzer0f384432012-08-21 00:52:01 +00001976namespace {
Richard Smith9f690bd2015-10-27 06:02:45 +00001977// An enum to represent whether something is dealing with a call to begin()
1978// or a call to end() in a range-based for loop.
1979enum BeginEndFunction {
1980 BEF_begin,
1981 BEF_end
1982};
Sam Panzer0f384432012-08-21 00:52:01 +00001983
Richard Smith02e85f32011-04-14 22:09:26 +00001984/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001985/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001986/// nor from the diagnostics produced when analysing the implicit expressions
1987/// required in a for-range statement.
1988void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Richard Smith9f690bd2015-10-27 06:02:45 +00001989 BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001990 CallExpr *CE = dyn_cast<CallExpr>(E);
1991 if (!CE)
1992 return;
1993 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1994 if (!D)
1995 return;
1996 SourceLocation Loc = D->getLocation();
1997
1998 std::string Description;
1999 bool IsTemplate = false;
2000 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2001 Description = SemaRef.getTemplateArgumentBindingsText(
2002 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2003 IsTemplate = true;
2004 }
2005
2006 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2007 << BEF << IsTemplate << Description << E->getType();
2008}
2009
Sam Panzer0f384432012-08-21 00:52:01 +00002010/// Build a variable declaration for a for-range statement.
2011VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2012 QualType Type, const char *Name) {
2013 DeclContext *DC = SemaRef.CurContext;
2014 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2015 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2016 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002017 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00002018 Decl->setImplicit();
2019 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00002020}
2021
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002022}
Richard Smith02e85f32011-04-14 22:09:26 +00002023
Fariborz Jahanian00213472012-07-06 19:04:04 +00002024static bool ObjCEnumerationCollection(Expr *Collection) {
2025 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00002026 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00002027}
2028
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002029/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002030///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002031/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00002032/// A range-based for statement is equivalent to
2033///
2034/// {
2035/// auto && __range = range-init;
2036/// for ( auto __begin = begin-expr,
2037/// __end = end-expr;
2038/// __begin != __end;
2039/// ++__begin ) {
2040/// for-range-declaration = *__begin;
2041/// statement
2042/// }
2043/// }
2044///
2045/// The body of the loop is not available yet, since it cannot be analysed until
2046/// we have determined the type of the for-range-declaration.
Richard Smith9f690bd2015-10-27 06:02:45 +00002047StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2048 SourceLocation CoawaitLoc, Stmt *First,
2049 SourceLocation ColonLoc, Expr *Range,
2050 SourceLocation RParenLoc,
2051 BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00002052 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00002053 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002054
Richard Smith3249fed2013-08-21 01:40:36 +00002055 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00002056 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002057
2058 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2059 assert(DS && "first part of for range not a decl stmt");
2060
2061 if (!DS->isSingleDecl()) {
2062 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
2063 return StmtError();
2064 }
Richard Smith02e85f32011-04-14 22:09:26 +00002065
Richard Smith3249fed2013-08-21 01:40:36 +00002066 Decl *LoopVar = DS->getSingleDecl();
2067 if (LoopVar->isInvalidDecl() || !Range ||
2068 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2069 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002070 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002071 }
Richard Smith02e85f32011-04-14 22:09:26 +00002072
Eric Fiselierb936a392017-06-14 03:24:55 +00002073 // Build the coroutine state immediately and not later during template
2074 // instantiation
2075 if (!CoawaitLoc.isInvalid()) {
2076 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2077 return StmtError();
Richard Smithcfd53b42015-10-22 06:13:50 +00002078 }
2079
Richard Smith02e85f32011-04-14 22:09:26 +00002080 // Build auto && __range = range-init
2081 SourceLocation RangeLoc = Range->getLocStart();
2082 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2083 Context.getAutoRRefDeductType(),
2084 "__range");
2085 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00002086 diag::err_for_range_deduction_failure)) {
2087 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002088 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002089 }
Richard Smith02e85f32011-04-14 22:09:26 +00002090
2091 // Claim the type doesn't contain auto: we've already done the checking.
2092 DeclGroupPtrTy RangeGroup =
Richard Smith3beb7c62017-01-12 02:27:38 +00002093 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
Richard Smith02e85f32011-04-14 22:09:26 +00002094 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00002095 if (RangeDecl.isInvalid()) {
2096 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00002097 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00002098 }
Richard Smith02e85f32011-04-14 22:09:26 +00002099
Richard Smithcfd53b42015-10-22 06:13:50 +00002100 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
Richard Smith01694c32016-03-20 10:33:40 +00002101 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2102 /*Cond=*/nullptr, /*Inc=*/nullptr,
2103 DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00002104}
2105
2106/// \brief Create the initialization, compare, and increment steps for
2107/// the range-based for loop expression.
2108/// This function does not handle array-based for loops,
2109/// which are created in Sema::BuildCXXForRangeStmt.
2110///
2111/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2112/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2113/// CandidateSet and BEF are set and some non-success value is returned on
2114/// failure.
Eric Fiselierb936a392017-06-14 03:24:55 +00002115static Sema::ForRangeStatus
2116BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2117 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2118 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2119 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2120 ExprResult *EndExpr, BeginEndFunction *BEF) {
Sam Panzer0f384432012-08-21 00:52:01 +00002121 DeclarationNameInfo BeginNameInfo(
2122 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2123 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2124 ColonLoc);
2125
2126 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2127 Sema::LookupMemberName);
2128 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2129
2130 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2131 // - if _RangeT is a class type, the unqualified-ids begin and end are
2132 // looked up in the scope of class _RangeT as if by class member access
2133 // lookup (3.4.5), and if either (or both) finds at least one
2134 // declaration, begin-expr and end-expr are __range.begin() and
2135 // __range.end(), respectively;
2136 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2137 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2138
2139 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2140 SourceLocation RangeLoc = BeginVar->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +00002141 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002142
2143 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2144 << RangeLoc << BeginRange->getType() << *BEF;
2145 return Sema::FRS_DiagnosticIssued;
2146 }
2147 } else {
2148 // - otherwise, begin-expr and end-expr are begin(__range) and
2149 // end(__range), respectively, where begin and end are looked up with
2150 // argument-dependent lookup (3.4.2). For the purposes of this name
2151 // lookup, namespace std is an associated namespace.
2152
2153 }
2154
Richard Smith9f690bd2015-10-27 06:02:45 +00002155 *BEF = BEF_begin;
Sam Panzer0f384432012-08-21 00:52:01 +00002156 Sema::ForRangeStatus RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002157 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002158 BeginMemberLookup, CandidateSet,
2159 BeginRange, BeginExpr);
2160
Richard Smith9f690bd2015-10-27 06:02:45 +00002161 if (RangeStatus != Sema::FRS_Success) {
2162 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2163 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2164 << ColonLoc << BEF_begin << BeginRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002165 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002166 }
Eric Fiselierb936a392017-06-14 03:24:55 +00002167 if (!CoawaitLoc.isInvalid()) {
2168 // FIXME: getCurScope() should not be used during template instantiation.
2169 // We should pick up the set of unqualified lookup results for operator
2170 // co_await during the initial parse.
2171 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2172 BeginExpr->get());
2173 if (BeginExpr->isInvalid())
2174 return Sema::FRS_DiagnosticIssued;
2175 }
Sam Panzer0f384432012-08-21 00:52:01 +00002176 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2177 diag::err_for_range_iter_deduction_failure)) {
2178 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2179 return Sema::FRS_DiagnosticIssued;
2180 }
2181
Richard Smith9f690bd2015-10-27 06:02:45 +00002182 *BEF = BEF_end;
Sam Panzer0f384432012-08-21 00:52:01 +00002183 RangeStatus =
Richard Smith9f690bd2015-10-27 06:02:45 +00002184 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
Sam Panzer0f384432012-08-21 00:52:01 +00002185 EndMemberLookup, CandidateSet,
2186 EndRange, EndExpr);
Richard Smith9f690bd2015-10-27 06:02:45 +00002187 if (RangeStatus != Sema::FRS_Success) {
2188 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2189 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2190 << ColonLoc << BEF_end << EndRange->getType();
Sam Panzer0f384432012-08-21 00:52:01 +00002191 return RangeStatus;
Richard Smith9f690bd2015-10-27 06:02:45 +00002192 }
Sam Panzer0f384432012-08-21 00:52:01 +00002193 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2194 diag::err_for_range_iter_deduction_failure)) {
2195 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2196 return Sema::FRS_DiagnosticIssued;
2197 }
2198 return Sema::FRS_Success;
2199}
2200
2201/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002202/// If the attempt fails, this function will return a valid, null StmtResult
2203/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002204static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2205 SourceLocation ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002206 SourceLocation CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002207 Stmt *LoopVarDecl,
2208 SourceLocation ColonLoc,
2209 Expr *Range,
2210 SourceLocation RangeLoc,
2211 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002212 // Determine whether we can rebuild the for-range statement with a
2213 // dereferenced range expression.
2214 ExprResult AdjustedRange;
2215 {
2216 Sema::SFINAETrap Trap(SemaRef);
2217
2218 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2219 if (AdjustedRange.isInvalid())
2220 return StmtResult();
2221
Richard Smith9f690bd2015-10-27 06:02:45 +00002222 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2223 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2224 RParenLoc, Sema::BFRK_Check);
Richard Smitha05b3b52012-09-20 21:52:32 +00002225 if (SR.isInvalid())
2226 return StmtResult();
2227 }
2228
2229 // The attempt to dereference worked well enough that it could produce a valid
2230 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2231 // case there are any other (non-fatal) problems with it.
2232 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2233 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
Richard Smith9f690bd2015-10-27 06:02:45 +00002234 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2235 ColonLoc, AdjustedRange.get(), RParenLoc,
Richard Smitha05b3b52012-09-20 21:52:32 +00002236 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002237}
2238
Richard Smith3249fed2013-08-21 01:40:36 +00002239namespace {
2240/// RAII object to automatically invalidate a declaration if an error occurs.
2241struct InvalidateOnErrorScope {
2242 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2243 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2244 ~InvalidateOnErrorScope() {
2245 if (Enabled && Trap.hasErrorOccurred())
2246 D->setInvalidDecl();
2247 }
2248
2249 DiagnosticErrorTrap Trap;
2250 Decl *D;
2251 bool Enabled;
2252};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002253}
Richard Smith3249fed2013-08-21 01:40:36 +00002254
Richard Smitha05b3b52012-09-20 21:52:32 +00002255/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002256StmtResult
Richard Smithcfd53b42015-10-22 06:13:50 +00002257Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
Richard Smith01694c32016-03-20 10:33:40 +00002258 SourceLocation ColonLoc, Stmt *RangeDecl,
2259 Stmt *Begin, Stmt *End, Expr *Cond,
Richard Smith02e85f32011-04-14 22:09:26 +00002260 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002261 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith9f690bd2015-10-27 06:02:45 +00002262 // FIXME: This should not be used during template instantiation. We should
2263 // pick up the set of unqualified lookup results for the != and + operators
2264 // in the initial parse.
2265 //
2266 // Testcase (accepts-invalid):
2267 // template<typename T> void f() { for (auto x : T()) {} }
2268 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2269 // bool operator!=(N::X, N::X); void operator++(N::X);
2270 // void g() { f<N::X>(); }
Richard Smith02e85f32011-04-14 22:09:26 +00002271 Scope *S = getCurScope();
2272
2273 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2274 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2275 QualType RangeVarType = RangeVar->getType();
2276
2277 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2278 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2279
Richard Smith3249fed2013-08-21 01:40:36 +00002280 // If we hit any errors, mark the loop variable as invalid if its type
2281 // contains 'auto'.
2282 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2283 LoopVar->getType()->isUndeducedType());
2284
Richard Smith01694c32016-03-20 10:33:40 +00002285 StmtResult BeginDeclStmt = Begin;
2286 StmtResult EndDeclStmt = End;
Richard Smith02e85f32011-04-14 22:09:26 +00002287 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2288
Richard Smith27d807c2013-04-30 13:56:41 +00002289 if (RangeVarType->isDependentType()) {
2290 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002291 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002292
2293 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2294 // them in properly when we instantiate the loop.
Erik Pilkington21ff3452017-06-12 16:11:06 +00002295 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2296 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2297 for (auto *Binding : DD->bindings())
2298 Binding->setType(Context.DependentTy);
Richard Smith27d807c2013-04-30 13:56:41 +00002299 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
Erik Pilkington21ff3452017-06-12 16:11:06 +00002300 }
Richard Smith01694c32016-03-20 10:33:40 +00002301 } else if (!BeginDeclStmt.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002302 SourceLocation RangeLoc = RangeVar->getLocation();
2303
Ted Kremenekbed648e2011-10-10 22:36:28 +00002304 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2305
2306 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2307 VK_LValue, ColonLoc);
2308 if (BeginRangeRef.isInvalid())
2309 return StmtError();
2310
2311 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2312 VK_LValue, ColonLoc);
2313 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002314 return StmtError();
2315
2316 QualType AutoType = Context.getAutoDeductType();
2317 Expr *Range = RangeVar->getInit();
2318 if (!Range)
2319 return StmtError();
2320 QualType RangeType = Range->getType();
2321
2322 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002323 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002324 return StmtError();
2325
2326 // Build auto __begin = begin-expr, __end = end-expr.
2327 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2328 "__begin");
2329 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2330 "__end");
2331
2332 // Build begin-expr and end-expr and attach to __begin and __end variables.
2333 ExprResult BeginExpr, EndExpr;
2334 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2335 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2336 // __range + __bound, respectively, where __bound is the array bound. If
2337 // _RangeT is an array of unknown size or an array of incomplete type,
2338 // the program is ill-formed;
2339
2340 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002341 BeginExpr = BeginRangeRef;
Eric Fiselierb936a392017-06-14 03:24:55 +00002342 if (!CoawaitLoc.isInvalid()) {
2343 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2344 if (BeginExpr.isInvalid())
2345 return StmtError();
2346 }
Ted Kremenekbed648e2011-10-10 22:36:28 +00002347 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002348 diag::err_for_range_iter_deduction_failure)) {
2349 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2350 return StmtError();
2351 }
2352
2353 // Find the array bound.
2354 ExprResult BoundExpr;
2355 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002356 BoundExpr = IntegerLiteral::Create(
2357 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002358 else if (const VariableArrayType *VAT =
Faisal Vali1ca2d962017-05-15 01:49:19 +00002359 dyn_cast<VariableArrayType>(UnqAT)) {
2360 // For a variably modified type we can't just use the expression within
2361 // the array bounds, since we don't want that to be re-evaluated here.
2362 // Rather, we need to determine what it was when the array was first
2363 // created - so we resort to using sizeof(vla)/sizeof(element).
2364 // For e.g.
2365 // void f(int b) {
2366 // int vla[b];
2367 // b = -1; <-- This should not affect the num of iterations below
2368 // for (int &c : vla) { .. }
2369 // }
2370
2371 // FIXME: This results in codegen generating IR that recalculates the
2372 // run-time number of elements (as opposed to just using the IR Value
2373 // that corresponds to the run-time value of each bound that was
2374 // generated when the array was created.) If this proves too embarassing
2375 // even for unoptimized IR, consider passing a magic-value/cookie to
2376 // codegen that then knows to simply use that initial llvm::Value (that
2377 // corresponds to the bound at time of array creation) within
2378 // getelementptr. But be prepared to pay the price of increasing a
2379 // customized form of coupling between the two components - which could
2380 // be hard to maintain as the codebase evolves.
2381
2382 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2383 EndVar->getLocation(), UETT_SizeOf,
2384 /*isType=*/true,
2385 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2386 VAT->desugar(), RangeLoc))
2387 .getAsOpaquePtr(),
2388 EndVar->getSourceRange());
2389 if (SizeOfVLAExprR.isInvalid())
2390 return StmtError();
2391
2392 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2393 EndVar->getLocation(), UETT_SizeOf,
2394 /*isType=*/true,
2395 CreateParsedType(VAT->desugar(),
2396 Context.getTrivialTypeSourceInfo(
2397 VAT->getElementType(), RangeLoc))
2398 .getAsOpaquePtr(),
2399 EndVar->getSourceRange());
2400 if (SizeOfEachElementExprR.isInvalid())
2401 return StmtError();
2402
2403 BoundExpr =
2404 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2405 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2406 if (BoundExpr.isInvalid())
2407 return StmtError();
2408
2409 } else {
Richard Smith02e85f32011-04-14 22:09:26 +00002410 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2411 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002412 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002413 }
2414
2415 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002416 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002417 BoundExpr.get());
2418 if (EndExpr.isInvalid())
2419 return StmtError();
2420 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2421 diag::err_for_range_iter_deduction_failure)) {
2422 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2423 return StmtError();
2424 }
2425 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002426 OverloadCandidateSet CandidateSet(RangeLoc,
2427 OverloadCandidateSet::CSK_Normal);
Richard Smith9f690bd2015-10-27 06:02:45 +00002428 BeginEndFunction BEFFailure;
Eric Fiselierb936a392017-06-14 03:24:55 +00002429 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2430 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2431 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2432 &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002433
Richard Smitha05b3b52012-09-20 21:52:32 +00002434 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002435 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002436 // If the range is being built from an array parameter, emit a
2437 // a diagnostic that it is being treated as a pointer.
2438 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2439 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2440 QualType ArrayTy = PVD->getOriginalType();
2441 QualType PointerTy = PVD->getType();
2442 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2443 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2444 << RangeLoc << PVD << ArrayTy << PointerTy;
2445 Diag(PVD->getLocation(), diag::note_declared_at);
2446 return StmtError();
2447 }
2448 }
2449 }
2450
2451 // If building the range failed, try dereferencing the range expression
2452 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002453 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
Richard Smithcfd53b42015-10-22 06:13:50 +00002454 CoawaitLoc,
Sam Panzer0f384432012-08-21 00:52:01 +00002455 LoopVarDecl, ColonLoc,
2456 Range, RangeLoc,
2457 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002458 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002459 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002460 }
2461
Sam Panzer0f384432012-08-21 00:52:01 +00002462 // Otherwise, emit diagnostics if we haven't already.
2463 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002464 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002465 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2466 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002467 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002468 }
2469 // Return an error if no fix was discovered.
2470 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002471 return StmtError();
2472 }
2473
Sam Panzer0f384432012-08-21 00:52:01 +00002474 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2475 "invalid range expression in for loop");
2476
2477 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith01694c32016-03-20 10:33:40 +00002478 // C++1z removes this restriction.
Richard Smith02e85f32011-04-14 22:09:26 +00002479 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2480 if (!Context.hasSameType(BeginType, EndType)) {
Richard Smith01694c32016-03-20 10:33:40 +00002481 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2482 ? diag::warn_for_range_begin_end_types_differ
2483 : diag::ext_for_range_begin_end_types_differ)
2484 << BeginType << EndType;
Richard Smith02e85f32011-04-14 22:09:26 +00002485 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2486 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2487 }
2488
Richard Smith01694c32016-03-20 10:33:40 +00002489 BeginDeclStmt =
2490 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2491 EndDeclStmt =
2492 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002493
Ted Kremenekbed648e2011-10-10 22:36:28 +00002494 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2495 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002496 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002497 if (BeginRef.isInvalid())
2498 return StmtError();
2499
Richard Smith02e85f32011-04-14 22:09:26 +00002500 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2501 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002502 if (EndRef.isInvalid())
2503 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002504
2505 // Build and check __begin != __end expression.
2506 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2507 BeginRef.get(), EndRef.get());
Richard Smith03a4aa32016-06-23 19:02:52 +00002508 if (!NotEqExpr.isInvalid())
2509 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2510 if (!NotEqExpr.isInvalid())
2511 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002512 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002513 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2514 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002515 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2516 if (!Context.hasSameType(BeginType, EndType))
2517 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2518 return StmtError();
2519 }
2520
2521 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002522 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2523 VK_LValue, ColonLoc);
2524 if (BeginRef.isInvalid())
2525 return StmtError();
2526
Richard Smith02e85f32011-04-14 22:09:26 +00002527 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002528 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
Eric Fiselierb936a392017-06-14 03:24:55 +00002529 // FIXME: getCurScope() should not be used during template instantiation.
2530 // We should pick up the set of unqualified lookup results for operator
2531 // co_await during the initial parse.
Richard Smith9f690bd2015-10-27 06:02:45 +00002532 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
Richard Smithcfd53b42015-10-22 06:13:50 +00002533 if (!IncrExpr.isInvalid())
2534 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
Richard Smith02e85f32011-04-14 22:09:26 +00002535 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002536 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2537 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002538 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2539 return StmtError();
2540 }
2541
2542 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002543 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2544 VK_LValue, ColonLoc);
2545 if (BeginRef.isInvalid())
2546 return StmtError();
2547
Richard Smith02e85f32011-04-14 22:09:26 +00002548 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2549 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002550 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2551 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002552 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2553 return StmtError();
2554 }
2555
Richard Smitha05b3b52012-09-20 21:52:32 +00002556 // Attach *__begin as initializer for VD. Don't touch it if we're just
2557 // trying to determine whether this would be a valid range.
2558 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith3beb7c62017-01-12 02:27:38 +00002559 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00002560 if (LoopVar->isInvalidDecl())
2561 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2562 }
2563 }
2564
Richard Smitha05b3b52012-09-20 21:52:32 +00002565 // Don't bother to actually allocate the result if we're just trying to
2566 // determine whether it would be valid.
2567 if (Kind == BFRK_Check)
2568 return StmtResult();
2569
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002570 return new (Context) CXXForRangeStmt(
Richard Smith01694c32016-03-20 10:33:40 +00002571 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2572 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
Richard Smith9f690bd2015-10-27 06:02:45 +00002573 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2574 ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002575}
2576
Chad Rosier02a84392012-08-10 17:56:09 +00002577/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002578/// statement.
2579StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2580 if (!S || !B)
2581 return StmtError();
2582 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002583
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002584 ForStmt->setBody(B);
2585 return S;
2586}
2587
Richard Trieu3e1d4832015-04-13 22:08:55 +00002588// Warn when the loop variable is a const reference that creates a copy.
2589// Suggest using the non-reference type for copies. If a copy can be prevented
2590// suggest the const reference type that would do so.
2591// For instance, given "for (const &Foo : Range)", suggest
2592// "for (const Foo : Range)" to denote a copy is made for the loop. If
2593// possible, also suggest "for (const &Bar : Range)" if this type prevents
2594// the copy altogether.
2595static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2596 const VarDecl *VD,
2597 QualType RangeInitType) {
2598 const Expr *InitExpr = VD->getInit();
2599 if (!InitExpr)
2600 return;
2601
2602 QualType VariableType = VD->getType();
2603
Tim Shen4a05bb82016-06-21 20:29:17 +00002604 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2605 if (!Cleanups->cleanupsHaveSideEffects())
2606 InitExpr = Cleanups->getSubExpr();
2607
Richard Trieu3e1d4832015-04-13 22:08:55 +00002608 const MaterializeTemporaryExpr *MTE =
2609 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2610
2611 // No copy made.
2612 if (!MTE)
2613 return;
2614
2615 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2616
2617 // Searching for either UnaryOperator for dereference of a pointer or
2618 // CXXOperatorCallExpr for handling iterators.
2619 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2620 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2621 E = CCE->getArg(0);
2622 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2623 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2624 E = ME->getBase();
2625 } else {
2626 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2627 E = MTE->GetTemporaryExpr();
2628 }
2629 E = E->IgnoreImpCasts();
2630 }
2631
2632 bool ReturnsReference = false;
2633 if (isa<UnaryOperator>(E)) {
2634 ReturnsReference = true;
2635 } else {
2636 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2637 const FunctionDecl *FD = Call->getDirectCallee();
2638 QualType ReturnType = FD->getReturnType();
2639 ReturnsReference = ReturnType->isReferenceType();
2640 }
2641
2642 if (ReturnsReference) {
2643 // Loop variable creates a temporary. Suggest either to go with
2644 // non-reference loop variable to indiciate a copy is made, or
2645 // the correct time to bind a const reference.
2646 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2647 << VD << VariableType << E->getType();
2648 QualType NonReferenceType = VariableType.getNonReferenceType();
2649 NonReferenceType.removeLocalConst();
2650 QualType NewReferenceType =
2651 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2652 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2653 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2654 } else {
2655 // The range always returns a copy, so a temporary is always created.
2656 // Suggest removing the reference from the loop variable.
2657 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2658 << VD << RangeInitType;
2659 QualType NonReferenceType = VariableType.getNonReferenceType();
2660 NonReferenceType.removeLocalConst();
2661 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2662 << NonReferenceType << VD->getSourceRange();
2663 }
2664}
2665
2666// Warns when the loop variable can be changed to a reference type to
2667// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2668// "for (const Foo &x : Range)" if this form does not make a copy.
2669static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2670 const VarDecl *VD) {
2671 const Expr *InitExpr = VD->getInit();
2672 if (!InitExpr)
2673 return;
2674
2675 QualType VariableType = VD->getType();
2676
2677 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2678 if (!CE->getConstructor()->isCopyConstructor())
2679 return;
2680 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2681 if (CE->getCastKind() != CK_LValueToRValue)
2682 return;
2683 } else {
2684 return;
2685 }
2686
2687 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2688 // should be emitted. Also, only ignore POD types with trivial copy
2689 // constructors.
2690 if (VariableType.isPODType(SemaRef.Context))
2691 return;
2692
2693 // Suggest changing from a const variable to a const reference variable
2694 // if doing so will prevent a copy.
2695 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2696 << VD << VariableType << InitExpr->getType();
2697 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2698 << SemaRef.Context.getLValueReferenceType(VariableType)
2699 << VD->getSourceRange();
2700}
2701
2702/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2703/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2704/// using "const foo x" to show that a copy is made
2705/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2706/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2707/// prevent the copy.
2708/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2709/// Suggest "const foo &x" to prevent the copy.
2710static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2711 const CXXForRangeStmt *ForStmt) {
2712 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2713 ForStmt->getLocStart()) &&
2714 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2715 ForStmt->getLocStart()) &&
2716 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2717 ForStmt->getLocStart())) {
2718 return;
2719 }
2720
2721 const VarDecl *VD = ForStmt->getLoopVariable();
2722 if (!VD)
2723 return;
2724
2725 QualType VariableType = VD->getType();
2726
2727 if (VariableType->isIncompleteType())
2728 return;
2729
2730 const Expr *InitExpr = VD->getInit();
2731 if (!InitExpr)
2732 return;
2733
2734 if (VariableType->isReferenceType()) {
2735 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2736 ForStmt->getRangeInit()->getType());
2737 } else if (VariableType.isConstQualified()) {
2738 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2739 }
2740}
2741
Richard Smith02e85f32011-04-14 22:09:26 +00002742/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2743/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2744/// body cannot be performed until after the type of the range variable is
2745/// determined.
2746StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2747 if (!S || !B)
2748 return StmtError();
2749
Fariborz Jahanian00213472012-07-06 19:04:04 +00002750 if (isa<ObjCForCollectionStmt>(S))
2751 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002752
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002753 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2754 ForStmt->setBody(B);
2755
2756 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2757 diag::warn_empty_range_based_for_body);
2758
Richard Trieu3e1d4832015-04-13 22:08:55 +00002759 DiagnoseForRangeVariableCopies(*this, ForStmt);
2760
Richard Smith02e85f32011-04-14 22:09:26 +00002761 return S;
2762}
2763
Chris Lattnercab02a62011-02-17 20:34:02 +00002764StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2765 SourceLocation LabelLoc,
2766 LabelDecl *TheDecl) {
2767 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002768 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002769 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002770}
Chris Lattner1c310502007-05-31 06:00:00 +00002771
John McCalldadc5752010-08-24 06:29:42 +00002772StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002773Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002774 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002775 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002776 if (!E->isTypeDependent()) {
2777 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002778 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002779 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002780 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002781 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2782 if (ExprRes.isInvalid())
2783 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002784 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002785 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002786 return StmtError();
2787 }
John McCalla95172b2010-08-01 00:26:45 +00002788
Richard Smith945f8d32013-01-14 22:39:08 +00002789 ExprResult ExprRes = ActOnFinishFullExpr(E);
2790 if (ExprRes.isInvalid())
2791 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002792 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002793
John McCallaab3e412010-08-25 08:40:02 +00002794 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002795
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002796 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002797}
2798
Nico Weberd64657f2015-03-09 02:47:59 +00002799static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2800 const Scope &DestScope) {
2801 if (!S.CurrentSEHFinally.empty() &&
2802 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2803 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2804 }
2805}
2806
John McCalldadc5752010-08-24 06:29:42 +00002807StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002808Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002809 Scope *S = CurScope->getContinueParent();
2810 if (!S) {
2811 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002812 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002813 }
Nico Weberd64657f2015-03-09 02:47:59 +00002814 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002815
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002816 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002817}
2818
John McCalldadc5752010-08-24 06:29:42 +00002819StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002820Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002821 Scope *S = CurScope->getBreakParent();
2822 if (!S) {
2823 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002824 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002825 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826 if (S->isOpenMPLoopScope())
2827 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2828 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002829 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002830
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002831 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002832}
2833
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002834/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002835/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002836///
Douglas Gregor5d369002011-01-21 18:05:27 +00002837/// \param ReturnType If we're determining the copy elision candidate for
2838/// a return statement, this is the return type of the function. If we're
2839/// determining the copy elision candidate for a throw expression, this will
2840/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002841///
Douglas Gregor5d369002011-01-21 18:05:27 +00002842/// \param E The expression being returned from the function or block, or
2843/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002844///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002845/// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2846/// id-expressions that could be moved out of the function to be considered NRVO
2847/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2848/// determine whether we should try to move as part of a return or throw (which
2849/// does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002850///
2851/// \returns The NRVO candidate variable, if the return statement may use the
2852/// NRVO, or NULL if there is no such candidate.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002853VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2854 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002855 if (!getLangOpts().CPlusPlus)
2856 return nullptr;
2857
2858 // - in a return statement in a function [where] ...
2859 // ... the expression is the name of a non-volatile automatic object ...
2860 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002861 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002862 return nullptr;
2863 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2864 if (!VD)
2865 return nullptr;
2866
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002867 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002868 return VD;
2869 return nullptr;
2870}
2871
2872bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002873 bool AllowParamOrMoveConstructible) {
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002874 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002875 // - in a return statement in a function with ...
2876 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002877 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002878 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002879 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002880 // ... the same cv-unqualified type as the function return type ...
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002881 // When considering moving this expression out, allow dissimilar types.
2882 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002883 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2884 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886
John McCall03318c12011-11-11 03:57:31 +00002887 // ...object (other than a function or catch-clause parameter)...
2888 if (VD->getKind() != Decl::Var &&
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002889 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002890 return false;
2891 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002892
John McCall03318c12011-11-11 03:57:31 +00002893 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002894 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002895
Akira Hatanaka6697eff2017-02-15 05:15:28 +00002896 // Return false if VD is a __block variable. We don't want to implicitly move
2897 // out of a __block variable during a return because we cannot assume the
2898 // variable will no longer be used.
2899 if (VD->hasAttr<BlocksAttr>()) return false;
2900
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002901 if (AllowParamOrMoveConstructible)
2902 return true;
2903
John McCall03318c12011-11-11 03:57:31 +00002904 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002905 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002906
John McCall03318c12011-11-11 03:57:31 +00002907 // Variables with higher required alignment than their type's ABI
2908 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002909 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002910 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002911 return false;
John McCall03318c12011-11-11 03:57:31 +00002912
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002913 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002914}
2915
Douglas Gregor626fbed2011-01-21 21:08:57 +00002916/// \brief Perform the initialization of a potentially-movable value, which
2917/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002918///
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002919/// This routine implements C++14 [class.copy]p32, which attempts to treat
Douglas Gregorf282a762011-01-21 19:38:21 +00002920/// returned lvalues as rvalues in certain cases (to prefer move construction),
2921/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002922ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002923Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2924 const VarDecl *NRVOCandidate,
2925 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002926 Expr *Value,
2927 bool AllowNRVO) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002928 // C++14 [class.copy]p32:
2929 // When the criteria for elision of a copy/move operation are met, but not for
2930 // an exception-declaration, and the object to be copied is designated by an
2931 // lvalue, or when the expression in a return statement is a (possibly
2932 // parenthesized) id-expression that names an object with automatic storage
2933 // duration declared in the body or parameter-declaration-clause of the
2934 // innermost enclosing function or lambda-expression, overload resolution to
2935 // select the constructor for the copy is first performed as if the object
2936 // were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002937 ExprResult Res = ExprError();
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002938
2939 if (AllowNRVO && !NRVOCandidate)
2940 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2941
2942 if (AllowNRVO && NRVOCandidate) {
2943 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2944 CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregorf282a762011-01-21 19:38:21 +00002946 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002948 InitializationKind Kind = InitializationKind::CreateCopy(
2949 Value->getLocStart(), Value->getLocStart());
2950
2951 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002952 if (Seq) {
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002953 for (const InitializationSequence::Step &Step : Seq.steps()) {
2954 if (!(Step.Kind ==
2955 InitializationSequence::SK_ConstructorInitialization ||
2956 (Step.Kind == InitializationSequence::SK_UserConversion &&
2957 isa<CXXConstructorDecl>(Step.Function.Function))))
Douglas Gregorf282a762011-01-21 19:38:21 +00002958 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002960 CXXConstructorDecl *Constructor =
2961 cast<CXXConstructorDecl>(Step.Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962
Douglas Gregorf282a762011-01-21 19:38:21 +00002963 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002964 = Constructor->getParamDecl(0)->getType()
2965 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002967 // [...] If the first overload resolution fails or was not performed, or
2968 // if the type of the first parameter of the selected constructor is not
Nico Weber0a234042017-05-05 17:15:08 +00002969 // an rvalue reference to the object's type (possibly cv-qualified),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002970 // overload resolution is performed again, considering the object as an
2971 // lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002973 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002974 NRVOCandidate->getType()))
Douglas Gregorf282a762011-01-21 19:38:21 +00002975 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976
Douglas Gregorf282a762011-01-21 19:38:21 +00002977 // Promote "AsRvalue" to the heap, since we now need this
2978 // expression node to persist.
Erik Pilkingtonfc235eb2016-06-30 23:09:13 +00002979 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2980 Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002981
Douglas Gregorf282a762011-01-21 19:38:21 +00002982 // Complete type-checking the initialization of the return type
2983 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002984 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002985 }
2986 }
2987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002988
Douglas Gregorf282a762011-01-21 19:38:21 +00002989 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002990 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002991 // (again) now with the return value expression as written.
2992 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002993 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Douglas Gregorf282a762011-01-21 19:38:21 +00002995 return Res;
2996}
2997
Richard Smith4db51c22013-09-25 05:02:54 +00002998/// \brief Determine whether the declared return type of the specified function
2999/// contains 'auto'.
3000static bool hasDeducedReturnType(FunctionDecl *FD) {
3001 const FunctionProtoType *FPT =
3002 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00003003 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003004}
3005
Eli Friedman34b49062012-01-26 03:00:14 +00003006/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3007/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00003008///
John McCalldadc5752010-08-24 06:29:42 +00003009StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00003010Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3011 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00003012 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00003013 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00003014 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00003015 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Richard Smithb130fe72016-06-23 19:16:49 +00003016 bool HasDeducedReturnType =
3017 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003018
Faisal Valid143a0c2017-04-01 21:30:49 +00003019 if (ExprEvalContexts.back().Context ==
3020 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003021 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3022 if (RetValExp) {
3023 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3024 if (ER.isInvalid())
3025 return StmtError();
3026 RetValExp = ER.get();
3027 }
3028 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3029 }
3030
3031 if (HasDeducedReturnType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003032 // In C++1y, the return type may involve 'auto'.
3033 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3034 FunctionDecl *FD = CurLambda->CallOperator;
3035 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00003036 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003037
3038 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3039 assert(AT && "lost auto type from lambda return type");
3040 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3041 FD->setInvalidDecl();
3042 return StmtError();
3043 }
Alp Toker314cc812014-01-25 16:55:45 +00003044 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00003045 } else if (CurCap->HasImplicitReturnType) {
3046 // For blocks/lambdas with implicit return types, we check each return
3047 // statement individually, and deduce the common return type when the block
3048 // or lambda is completed.
3049 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00003050 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00003051 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3052 if (Result.isInvalid())
3053 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003054 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003055
Richard Smith5a0e50c2014-12-19 22:10:51 +00003056 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3057 // when deducing a return type for a lambda-expression (or by extension
3058 // for a block). These rules differ from the stated C++11 rules only in
3059 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00003060 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00003061 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00003062 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00003063 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00003064 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00003065 if (RetValExp) {
3066 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3067 // initializer list, because it is not an expression (even
3068 // though we represent it as one). We still deduce 'void'.
3069 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3070 << RetValExp->getSourceRange();
3071 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003072
Jordan Rosed39e5f12012-07-02 21:19:23 +00003073 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00003074 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00003075
3076 // Although we'll properly infer the type of the block once it's completed,
3077 // make sure we provide a return type now for better error recovery.
3078 if (CurCap->ReturnType.isNull())
3079 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00003080 }
Eli Friedman34b49062012-01-26 03:00:14 +00003081 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00003082
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003083 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00003084 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3085 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3086 return StmtError();
3087 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003088 } else if (CapturedRegionScopeInfo *CurRegion =
3089 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3090 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3091 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003092 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00003093 assert(CurLambda && "unknown kind of captured scope");
3094 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3095 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00003096 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3097 return StmtError();
3098 }
3099 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00003100
Steve Naroffc540d662008-09-03 18:15:37 +00003101 // Otherwise, verify that this result type matches the previous one. We are
3102 // pickier with blocks than for normal functions because we don't have GCC
3103 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00003104 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003105 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00003106 // Delay processing for now. TODO: there are lots of dependent
3107 // types we can conclusively prove aren't void.
3108 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00003109 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003110 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00003111 (RetValExp->isTypeDependent() ||
3112 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003113 if (!getLangOpts().CPlusPlus &&
3114 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00003115 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003116 else {
3117 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00003118 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00003119 }
Steve Naroffc540d662008-09-03 18:15:37 +00003120 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003121 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00003122 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3123 } else if (!RetValExp->isTypeDependent()) {
3124 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00003125
John McCall5500ef22011-08-17 22:09:46 +00003126 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3127 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3128 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00003129
John McCall5500ef22011-08-17 22:09:46 +00003130 // In C++ the return statement is handled via a copy initialization.
3131 // the C version of which boils down to CheckSingleAssignmentConstraints.
3132 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3133 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3134 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003135 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00003136 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3137 FnRetType, RetValExp);
3138 if (Res.isInvalid()) {
3139 // FIXME: Cleanup temporaries here, anyway?
3140 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00003141 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003142 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003143 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003144 } else {
3145 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00003146 }
Sebastian Redl573feed2009-01-18 13:19:59 +00003147
John McCall75f92b52011-08-17 21:34:14 +00003148 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003149 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3150 if (ER.isInvalid())
3151 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003152 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00003153 }
John McCall5500ef22011-08-17 22:09:46 +00003154 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3155 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00003156
Jordan Rosed39e5f12012-07-02 21:19:23 +00003157 // If we need to check for the named return value optimization,
3158 // or if we need to infer the return type,
3159 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003160 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003161 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162
Richard Smith9f690bd2015-10-27 06:02:45 +00003163 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3164 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3165
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003166 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00003167}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003168
Nico Weber72889432014-09-06 01:25:55 +00003169namespace {
3170/// \brief Marks all typedefs in all local classes in a type referenced.
3171///
3172/// In a function like
3173/// auto f() {
3174/// struct S { typedef int a; };
3175/// return S();
3176/// }
3177///
3178/// the local type escapes and could be referenced in some TUs but not in
3179/// others. Pretend that all local typedefs are always referenced, to not warn
3180/// on this. This isn't necessary if f has internal linkage, or the typedef
3181/// is private.
3182class LocalTypedefNameReferencer
3183 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3184public:
3185 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3186 bool VisitRecordType(const RecordType *RT);
3187private:
3188 Sema &S;
3189};
3190bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3191 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3192 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3193 R->isDependentType())
3194 return true;
3195 for (auto *TmpD : R->decls())
3196 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3197 if (T->getAccess() != AS_private || R->hasFriends())
3198 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3199 return true;
3200}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003201}
Nico Weber72889432014-09-06 01:25:55 +00003202
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003203TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003204 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003205 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3206 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00003207 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003208}
3209
Richard Smith2a7d4812013-05-04 07:00:32 +00003210/// Deduce the return type for a function from a returned expression, per
3211/// C++1y [dcl.spec.auto]p6.
3212bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3213 SourceLocation ReturnLoc,
3214 Expr *&RetExpr,
3215 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00003216 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00003217 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003218
Richard Smithc58f38f2013-08-14 20:16:31 +00003219 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3220 // If the deduction is for a return statement and the initializer is
3221 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00003222 Diag(RetExpr->getExprLoc(),
3223 getCurLambda() ? diag::err_lambda_return_init_list
3224 : diag::err_auto_fn_return_init_list)
3225 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00003226 return true;
3227 }
3228
3229 if (FD->isDependentContext()) {
3230 // C++1y [dcl.spec.auto]p12:
3231 // Return type deduction [...] occurs when the definition is
3232 // instantiated even if the function body contains a return
3233 // statement with a non-type-dependent operand.
3234 assert(AT->isDeduced() && "should have deduced to dependent type");
3235 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003236 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003237
Douglas Gregor6032d5b2015-10-01 19:52:44 +00003238 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003239 // Otherwise, [...] deduce a value for U using the rules of template
3240 // argument deduction.
3241 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3242
3243 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3244 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3245 << OrigResultType.getType() << RetExpr->getType();
3246
3247 if (DAR != DAR_Succeeded)
3248 return true;
Nico Weber72889432014-09-06 01:25:55 +00003249
3250 // If a local type is part of the returned type, mark its fields as
3251 // referenced.
3252 LocalTypedefNameReferencer Referencer(*this);
3253 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003254 } else {
3255 // In the case of a return with no operand, the initializer is considered
3256 // to be void().
3257 //
3258 // Deduction here can only succeed if the return type is exactly 'cv auto'
3259 // or 'decltype(auto)', so just check for that case directly.
3260 if (!OrigResultType.getType()->getAs<AutoType>()) {
3261 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3262 << OrigResultType.getType();
3263 return true;
3264 }
3265 // We always deduce U = void in this case.
3266 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3267 if (Deduced.isNull())
3268 return true;
3269 }
3270
3271 // If a function with a declared return type that contains a placeholder type
3272 // has multiple return statements, the return type is deduced for each return
3273 // statement. [...] if the type deduced is not the same in each deduction,
3274 // the program is ill-formed.
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003275 QualType DeducedT = AT->getDeducedType();
3276 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003277 AutoType *NewAT = Deduced->getContainedAutoType();
Manman Renb4e8a1b2016-02-04 20:05:40 +00003278 // It is possible that NewAT->getDeducedType() is null. When that happens,
3279 // we should not crash, instead we ignore this deduction.
3280 if (NewAT->getDeducedType().isNull())
3281 return false;
3282
Douglas Gregora602a152015-10-01 20:20:47 +00003283 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003284 DeducedT);
Douglas Gregora602a152015-10-01 20:20:47 +00003285 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3286 NewAT->getDeducedType());
3287 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
Richard Smith4db51c22013-09-25 05:02:54 +00003288 const LambdaScopeInfo *LambdaSI = getCurLambda();
3289 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3290 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003291 << NewAT->getDeducedType() << DeducedT
Richard Smith4db51c22013-09-25 05:02:54 +00003292 << true /*IsLambda*/;
3293 } else {
3294 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3295 << (AT->isDecltypeAuto() ? 1 : 0)
Argyrios Kyrtzidisb4030df2016-01-30 01:51:20 +00003296 << NewAT->getDeducedType() << DeducedT;
Richard Smith4db51c22013-09-25 05:02:54 +00003297 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003298 return true;
3299 }
3300 } else if (!FD->isInvalidDecl()) {
3301 // Update all declarations of the function to have the deduced return type.
3302 Context.adjustDeducedFunctionResultType(FD, Deduced);
3303 }
3304
3305 return false;
3306}
3307
John McCalldadc5752010-08-24 06:29:42 +00003308StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003309Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3310 Scope *CurScope) {
3311 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
Faisal Valid143a0c2017-04-01 21:30:49 +00003312 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3313 ExpressionEvaluationContext::DiscardedStatement)
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003314 return R;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003315
3316 if (VarDecl *VD =
3317 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3318 CurScope->addNRVOCandidate(VD);
3319 } else {
3320 CurScope->setNoNRVO();
3321 }
3322
Nico Weberd64657f2015-03-09 02:47:59 +00003323 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3324
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003325 return R;
3326}
3327
3328StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003329 // Check for unexpanded parameter packs.
3330 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3331 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003332
Eli Friedman34b49062012-01-26 03:00:14 +00003333 if (isa<CapturingScopeInfo>(getCurFunction()))
3334 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003335
Chris Lattner79413952008-12-04 23:50:19 +00003336 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003337 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003338 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003339 bool isObjCMethod = false;
3340
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003341 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003342 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003343 if (FD->hasAttrs())
3344 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003345 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003346 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003347 << FD->getDeclName();
Richard Smith9bb192e2016-11-29 01:35:17 +00003348 if (FD->isMain() && RetValExp)
3349 if (isa<CXXBoolLiteralExpr>(RetValExp))
3350 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3351 << RetValExp->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00003352 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003353 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003354 isObjCMethod = true;
3355 if (MD->hasAttrs())
3356 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003357 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3358 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003359 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003360 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003361 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3362 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003363 }
3364 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003365 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003366
Richard Smithb130fe72016-06-23 19:16:49 +00003367 // C++1z: discarded return statements are not considered when deducing a
3368 // return type.
Faisal Valid143a0c2017-04-01 21:30:49 +00003369 if (ExprEvalContexts.back().Context ==
3370 ExpressionEvaluationContext::DiscardedStatement &&
Richard Smithb130fe72016-06-23 19:16:49 +00003371 FnRetType->getContainedAutoType()) {
3372 if (RetValExp) {
3373 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3374 if (ER.isInvalid())
3375 return StmtError();
3376 RetValExp = ER.get();
3377 }
3378 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3379 }
3380
Richard Smith2a7d4812013-05-04 07:00:32 +00003381 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3382 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003383 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003384 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3385 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003386 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003387 FD->setInvalidDecl();
3388 return StmtError();
3389 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003390 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003391 }
3392 }
3393 }
3394
Richard Smithc58f38f2013-08-14 20:16:31 +00003395 bool HasDependentReturnType = FnRetType->isDependentType();
3396
Craig Topperc3ec1492014-05-26 06:22:03 +00003397 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003398 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003399 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003400 if (isa<InitListExpr>(RetValExp)) {
3401 // We simply never allow init lists as the return value of void
3402 // functions. This is compatible because this was never allowed before,
3403 // so there's no legacy code to deal with.
3404 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3405 int FunctionKind = 0;
3406 if (isa<ObjCMethodDecl>(CurDecl))
3407 FunctionKind = 1;
3408 else if (isa<CXXConstructorDecl>(CurDecl))
3409 FunctionKind = 2;
3410 else if (isa<CXXDestructorDecl>(CurDecl))
3411 FunctionKind = 3;
3412
3413 Diag(ReturnLoc, diag::err_return_init_list)
3414 << CurDecl->getDeclName() << FunctionKind
3415 << RetValExp->getSourceRange();
3416
3417 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003418 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003419 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003420 // C99 6.8.6.4p1 (ext_ since GCC warns)
3421 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003422 if (RetValExp->getType()->isVoidType()) {
3423 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3424 if (isa<CXXConstructorDecl>(CurDecl) ||
3425 isa<CXXDestructorDecl>(CurDecl))
3426 D = diag::err_ctor_dtor_returns_void;
3427 else
3428 D = diag::ext_return_has_void_expr;
3429 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003430 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003431 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003432 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003433 if (Result.isInvalid())
3434 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003435 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003436 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003437 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003438 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003439 // return of void in constructor/destructor is illegal in C++.
3440 if (D == diag::err_ctor_dtor_returns_void) {
3441 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3442 Diag(ReturnLoc, D)
3443 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3444 << RetValExp->getSourceRange();
3445 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003446 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003447 else if (D != diag::ext_return_has_void_expr ||
Craig Topper8f7f3ea2015-11-17 05:40:05 +00003448 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003449 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003450
3451 int FunctionKind = 0;
3452 if (isa<ObjCMethodDecl>(CurDecl))
3453 FunctionKind = 1;
3454 else if (isa<CXXConstructorDecl>(CurDecl))
3455 FunctionKind = 2;
3456 else if (isa<CXXDestructorDecl>(CurDecl))
3457 FunctionKind = 3;
3458
Nick Lewycky1be750a2011-06-01 07:44:31 +00003459 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003460 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003461 << RetValExp->getSourceRange();
3462 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003463 }
Mike Stump11289f42009-09-09 15:08:12 +00003464
Sebastian Redleef474c2012-02-22 10:50:08 +00003465 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003466 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3467 if (ER.isInvalid())
3468 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003469 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003470 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Craig Topperc3ec1492014-05-26 06:22:03 +00003473 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003474 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003475 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003476
David Majnemer2887ad32014-12-13 08:12:56 +00003477 unsigned DiagID;
3478 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3479 // C++11 [stmt.return]p2
3480 DiagID = diag::err_constexpr_return_missing_expr;
3481 FD->setInvalidDecl();
3482 } else if (getLangOpts().C99) {
3483 // C99 6.8.6.4p1 (ext_ since GCC warns)
3484 DiagID = diag::ext_return_missing_expr;
3485 } else {
3486 // C90 6.6.6.4p4
3487 DiagID = diag::warn_return_missing_expr;
3488 }
3489
3490 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003491 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003492 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003493 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003494
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003495 Result = new (Context) ReturnStmt(ReturnLoc);
3496 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003497 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003498 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003499
3500 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3501
3502 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3503 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3504 // function return.
3505
3506 // In C++ the return statement is handled via a copy initialization,
3507 // the C version of which boils down to CheckSingleAssignmentConstraints.
3508 if (RetValExp)
3509 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003510 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003511 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003512 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003513 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003514 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003516 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003517 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003518 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003519 return StmtError();
3520 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003521 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003522
3523 // If we have a related result type, we need to implicitly
3524 // convert back to the formal result type. We can't pretend to
3525 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003526 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003527 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003528 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3529 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003530 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3531 if (Res.isInvalid()) {
3532 // FIXME: Clean up temporaries here anyway?
3533 return StmtError();
3534 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003535 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003536 }
3537
Artyom Skrobov9f213442014-01-24 11:10:39 +00003538 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3539 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
John McCallacf0ee52010-10-08 02:01:28 +00003542 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003543 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3544 if (ER.isInvalid())
3545 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003546 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003547 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003548 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
3551 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003552 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003553 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003554 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003555
Richard Smith9f690bd2015-10-27 06:02:45 +00003556 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3557 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3558
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003559 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003560}
3561
John McCalldadc5752010-08-24 06:29:42 +00003562StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003563Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003564 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003565 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003566 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003567 if (Var && Var->isInvalidDecl())
3568 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003570 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003571}
3572
John McCalldadc5752010-08-24 06:29:42 +00003573StmtResult
John McCallb268a282010-08-23 23:25:46 +00003574Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003575 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003576}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003577
John McCalldadc5752010-08-24 06:29:42 +00003578StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003580 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003582 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3583
John McCallaab3e412010-08-25 08:40:02 +00003584 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003585 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003586 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3587 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003588}
3589
John McCall0bd3e402012-05-08 21:41:25 +00003590StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003591 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003592 ExprResult Result = DefaultLvalueConversion(Throw);
3593 if (Result.isInvalid())
3594 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003595
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003596 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003597 if (Result.isInvalid())
3598 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003599 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003600
Douglas Gregor2900c162010-04-22 21:44:01 +00003601 QualType ThrowType = Throw->getType();
3602 // Make sure the expression type is an ObjC pointer or "void *".
3603 if (!ThrowType->isDependentType() &&
3604 !ThrowType->isObjCObjectPointerType()) {
3605 const PointerType *PT = ThrowType->getAs<PointerType>();
3606 if (!PT || !PT->getPointeeType()->isVoidType())
Richard Smithf8812672016-12-02 22:38:31 +00003607 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
Douglas Gregor2900c162010-04-22 21:44:01 +00003608 << Throw->getType() << Throw->getSourceRange());
3609 }
3610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003612 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003613}
3614
John McCalldadc5752010-08-24 06:29:42 +00003615StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003617 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003618 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003619 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3620
John McCallb268a282010-08-23 23:25:46 +00003621 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003622 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003623 // in the context of an @catch clause).
3624 Scope *AtCatchParent = CurScope;
3625 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3626 AtCatchParent = AtCatchParent->getParent();
3627 if (!AtCatchParent)
Richard Smithf8812672016-12-02 22:38:31 +00003628 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003629 }
John McCallb268a282010-08-23 23:25:46 +00003630 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003631}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003632
John McCalld9bb7432011-07-27 21:50:02 +00003633ExprResult
3634Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3635 ExprResult result = DefaultLvalueConversion(operand);
3636 if (result.isInvalid())
3637 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003638 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003639
3640 // Make sure the expression type is an ObjC pointer or "void *".
3641 QualType type = operand->getType();
3642 if (!type->isDependentType() &&
3643 !type->isObjCObjectPointerType()) {
3644 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003645 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3646 if (getLangOpts().CPlusPlus) {
3647 if (RequireCompleteType(atLoc, type,
3648 diag::err_incomplete_receiver_type))
Richard Smithf8812672016-12-02 22:38:31 +00003649 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003650 << type << operand->getSourceRange();
3651
3652 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
Richard Smithe15a3702016-10-06 23:12:58 +00003653 if (result.isInvalid())
3654 return ExprError();
Jordan Rose5790d522014-08-12 16:20:36 +00003655 if (!result.isUsable())
Richard Smithf8812672016-12-02 22:38:31 +00003656 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003657 << type << operand->getSourceRange();
3658
3659 operand = result.get();
3660 } else {
Richard Smithf8812672016-12-02 22:38:31 +00003661 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
Jordan Rose5790d522014-08-12 16:20:36 +00003662 << type << operand->getSourceRange();
3663 }
3664 }
John McCalld9bb7432011-07-27 21:50:02 +00003665 }
3666
3667 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003668 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003669}
3670
John McCalldadc5752010-08-24 06:29:42 +00003671StmtResult
John McCallb268a282010-08-23 23:25:46 +00003672Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3673 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003674 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003675 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003676 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003677}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003678
3679/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3680/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003681StmtResult
John McCall48871652010-08-21 09:40:31 +00003682Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003683 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003684 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003685 return new (Context)
3686 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003687}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003688
John McCall31168b02011-06-15 23:02:42 +00003689StmtResult
3690Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3691 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003692 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003693}
3694
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003695namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003696class CatchHandlerType {
3697 QualType QT;
3698 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003699
Aaron Ballman8aee642902015-04-08 00:05:29 +00003700 // This is a special constructor to be used only with DenseMapInfo's
3701 // getEmptyKey() and getTombstoneKey() functions.
3702 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3703 enum Unique { ForDenseMap };
3704 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3705
Sebastian Redl63c4da02009-07-29 17:15:45 +00003706public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003707 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003708 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003709 /// level pointer and cv-qualifiers.
3710 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3711 if (QT->isPointerType())
3712 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003713
Aaron Ballman8aee642902015-04-08 00:05:29 +00003714 if (IsPointer || QT->isReferenceType())
3715 QT = QT->getPointeeType();
3716 QT = QT.getUnqualifiedType();
3717 }
3718
3719 /// Used when creating a CatchHandlerType from a base class type; pretends the
3720 /// type passed in had the pointer qualifier, does not need to get an
3721 /// unqualified type.
3722 CatchHandlerType(QualType QT, bool IsPointer)
3723 : QT(QT), IsPointer(IsPointer) {}
3724
3725 QualType underlying() const { return QT; }
3726 bool isPointer() const { return IsPointer; }
3727
3728 friend bool operator==(const CatchHandlerType &LHS,
3729 const CatchHandlerType &RHS) {
3730 // If the pointer qualification does not match, we can return early.
3731 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003732 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003733 // Otherwise, check the underlying type without cv-qualifiers.
3734 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003735 }
3736};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003737} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003738
Aaron Ballman8aee642902015-04-08 00:05:29 +00003739namespace llvm {
3740template <> struct DenseMapInfo<CatchHandlerType> {
3741 static CatchHandlerType getEmptyKey() {
3742 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3743 CatchHandlerType::ForDenseMap);
3744 }
3745
3746 static CatchHandlerType getTombstoneKey() {
3747 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3748 CatchHandlerType::ForDenseMap);
3749 }
3750
3751 static unsigned getHashValue(const CatchHandlerType &Base) {
3752 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3753 }
3754
3755 static bool isEqual(const CatchHandlerType &LHS,
3756 const CatchHandlerType &RHS) {
3757 return LHS == RHS;
3758 }
3759};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003760}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003761
3762namespace {
3763class CatchTypePublicBases {
3764 ASTContext &Ctx;
3765 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3766 const bool CheckAgainstPointer;
3767
3768 CXXCatchStmt *FoundHandler;
3769 CanQualType FoundHandlerType;
3770
3771public:
3772 CatchTypePublicBases(
3773 ASTContext &Ctx,
3774 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3775 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3776 FoundHandler(nullptr) {}
3777
3778 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3779 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3780
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003781 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003782 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003783 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
Benjamin Kramer536ffdf2016-02-13 15:49:17 +00003784 const auto &M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003785 auto I = M.find(Check);
3786 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003787 FoundHandler = I->second;
3788 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003789 return true;
3790 }
3791 }
3792 return false;
3793 }
3794};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003795}
Dan Gohman28ade552010-07-26 21:25:24 +00003796
Sebastian Redl9b244a82008-12-22 21:35:02 +00003797/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3798/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003799StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3800 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003801 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003802 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003803 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003804 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003805
Justin Lebar2a8db342016-09-28 22:45:54 +00003806 // Exceptions aren't allowed in CUDA device code.
3807 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +00003808 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3809 << "try" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +00003810
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003811 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3812 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3813
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003814 sema::FunctionScopeInfo *FSI = getCurFunction();
3815
Reid Klecknere7175912015-02-02 22:15:31 +00003816 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003817 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003818 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003819 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003820 }
3821
Robert Wilhelmcafda822013-08-22 09:20:03 +00003822 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003823 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003824 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003825
Aaron Ballman8aee642902015-04-08 00:05:29 +00003826 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003827 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003828 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003829
Aaron Ballman8aee642902015-04-08 00:05:29 +00003830 // Diagnose when the handler is a catch-all handler, but it isn't the last
3831 // handler for the try block. [except.handle]p5. Also, skip exception
3832 // declarations that are invalid, since we can't usefully report on them.
3833 if (!H->getExceptionDecl()) {
3834 if (i < NumHandlers - 1)
3835 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003836 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003837 } else if (H->getExceptionDecl()->isInvalidDecl())
3838 continue;
3839
3840 // Walk the type hierarchy to diagnose when this type has already been
3841 // handled (duplication), or cannot be handled (derivation inversion). We
3842 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003843 CatchHandlerType HandlerCHT =
3844 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003845
3846 // We can ignore whether the type is a reference or a pointer; we need the
3847 // underlying declaration type in order to get at the underlying record
3848 // decl, if there is one.
3849 QualType Underlying = HandlerCHT.underlying();
3850 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3851 if (!RD->hasDefinition())
3852 continue;
3853 // Check that none of the public, unambiguous base classes are in the
3854 // map ([except.handle]p1). Give the base classes the same pointer
3855 // qualification as the original type we are basing off of. This allows
3856 // comparison against the handler type using the same top-level pointer
3857 // as the original type.
3858 CXXBasePaths Paths;
3859 Paths.setOrigin(RD);
3860 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003861 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003862 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3863 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3864 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3865 diag::warn_exception_caught_by_earlier_handler)
3866 << H->getCaughtType();
3867 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3868 diag::note_previous_exception_handler)
3869 << Problem->getCaughtType();
3870 }
3871 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003872 }
Mike Stump11289f42009-09-09 15:08:12 +00003873
Aaron Ballman8aee642902015-04-08 00:05:29 +00003874 // Add the type the list of ones we have handled; diagnose if we've already
3875 // handled it.
3876 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3877 if (!R.second) {
3878 const CXXCatchStmt *Problem = R.first->second;
3879 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3880 diag::warn_exception_caught_by_earlier_handler)
3881 << H->getCaughtType();
3882 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3883 diag::note_previous_exception_handler)
3884 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003885 }
3886 }
Mike Stump11289f42009-09-09 15:08:12 +00003887
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003888 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003889
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003890 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003891}
John Wiegley1c0675e2011-04-28 01:08:34 +00003892
Reid Klecknere7175912015-02-02 22:15:31 +00003893StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3894 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003895 assert(TryBlock && Handler);
3896
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003897 sema::FunctionScopeInfo *FSI = getCurFunction();
3898
Reid Klecknere7175912015-02-02 22:15:31 +00003899 // SEH __try is incompatible with C++ try. Borland appears to support this,
3900 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003901 if (!getLangOpts().Borland) {
3902 if (FSI->FirstCXXTryLoc.isValid()) {
3903 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3904 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3905 }
Reid Klecknere7175912015-02-02 22:15:31 +00003906 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003907
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003908 FSI->setHasSEHTry(TryLoc);
3909
3910 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3911 // track if they use SEH.
3912 DeclContext *DC = CurContext;
3913 while (DC && !DC->isFunctionOrMethod())
3914 DC = DC->getParent();
3915 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3916 if (FD)
3917 FD->setUsesSEHTry(true);
3918 else
3919 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003920
Reid Kleckner8819a402015-07-10 00:16:25 +00003921 // Reject __try on unsupported targets.
3922 if (!Context.getTargetInfo().isSEHTrySupported())
3923 Diag(TryLoc, diag::err_seh_try_unsupported);
3924
Reid Klecknere7175912015-02-02 22:15:31 +00003925 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003926}
3927
3928StmtResult
3929Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3930 Expr *FilterExpr,
3931 Stmt *Block) {
3932 assert(FilterExpr && Block);
3933
3934 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003935 return StmtError(Diag(FilterExpr->getExprLoc(),
3936 diag::err_filter_expression_integral)
3937 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003938 }
3939
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003940 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003941}
3942
Nico Weberd64657f2015-03-09 02:47:59 +00003943void Sema::ActOnStartSEHFinallyBlock() {
3944 CurrentSEHFinally.push_back(CurScope);
3945}
3946
Nico Weberce903292015-03-09 03:17:15 +00003947void Sema::ActOnAbortSEHFinallyBlock() {
3948 CurrentSEHFinally.pop_back();
3949}
3950
Nico Weberd64657f2015-03-09 02:47:59 +00003951StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003952 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003953 CurrentSEHFinally.pop_back();
3954 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003955}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003956
Nico Weberc7d05962014-07-06 22:32:59 +00003957StmtResult
3958Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003959 Scope *SEHTryParent = CurScope;
3960 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3961 SEHTryParent = SEHTryParent->getParent();
3962 if (!SEHTryParent)
3963 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003964 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003965
Nico Weber9b982072014-07-07 00:12:30 +00003966 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003967}
3968
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003969StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3970 bool IsIfExists,
3971 NestedNameSpecifierLoc QualifierLoc,
3972 DeclarationNameInfo NameInfo,
3973 Stmt *Nested)
3974{
3975 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003976 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003977 cast<CompoundStmt>(Nested));
3978}
3979
3980
Chad Rosier02a84392012-08-10 17:56:09 +00003981StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003982 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003983 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003984 UnqualifiedId &Name,
3985 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003986 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003987 SS.getWithLocInContext(Context),
3988 GetNameFromUnqualifiedId(Name),
3989 Nested);
3990}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003991
3992RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003993Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3994 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003995 DeclContext *DC = CurContext;
3996 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3997 DC = DC->getParent();
3998
Craig Topperc3ec1492014-05-26 06:22:03 +00003999 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004000 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00004001 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4002 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004003 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004004 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004005
Alexey Bataev330de032014-10-29 12:21:55 +00004006 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004007 DC->addDecl(RD);
4008 RD->setImplicit();
4009 RD->startDefinition();
4010
Alexey Bataev9959db52014-05-06 10:08:46 +00004011 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00004012 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004013 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004014 return RD;
4015}
4016
4017static void buildCapturedStmtCaptureList(
4018 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4019 SmallVectorImpl<Expr *> &CaptureInits,
4020 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
4021
4022 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
4023 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
4024
4025 if (Cap->isThisCapture()) {
4026 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
4027 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00004028 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004029 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00004030 } else if (Cap->isVLATypeCapture()) {
4031 Captures.push_back(
4032 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
4033 CaptureInits.push_back(nullptr);
4034 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004035 }
4036
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004037 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
Samuel Antao4af1b7b2015-12-02 17:44:43 +00004038 Cap->isReferenceCapture()
4039 ? CapturedStmt::VCK_ByRef
4040 : CapturedStmt::VCK_ByCopy,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004041 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00004042 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004043 }
4044}
4045
4046void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00004047 CapturedRegionKind Kind,
4048 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00004049 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00004050 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004051
Alexey Bataev9959db52014-05-06 10:08:46 +00004052 // Build the context parameter
4053 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4054 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4055 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004056 auto *Param =
4057 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4058 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004059 DC->addDecl(Param);
4060
4061 CD->setContextParam(0, Param);
4062
4063 // Enter the capturing scope for this captured region.
4064 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4065
4066 if (CurScope)
4067 PushDeclContext(CurScope, CD);
4068 else
4069 CurContext = CD;
4070
Faisal Valid143a0c2017-04-01 21:30:49 +00004071 PushExpressionEvaluationContext(
4072 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev9959db52014-05-06 10:08:46 +00004073}
4074
4075void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4076 CapturedRegionKind Kind,
4077 ArrayRef<CapturedParamNameType> Params) {
4078 CapturedDecl *CD = nullptr;
4079 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4080
4081 // Build the context parameter
4082 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4083 bool ContextIsFound = false;
4084 unsigned ParamNum = 0;
4085 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4086 E = Params.end();
4087 I != E; ++I, ++ParamNum) {
4088 if (I->second.isNull()) {
4089 assert(!ContextIsFound &&
4090 "null type has been found already for '__context' parameter");
4091 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4092 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004093 auto *Param =
4094 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4095 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004096 DC->addDecl(Param);
4097 CD->setContextParam(ParamNum, Param);
4098 ContextIsFound = true;
4099 } else {
4100 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
Alexey Bataev56223232017-06-09 13:40:18 +00004101 auto *Param =
4102 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4103 ImplicitParamDecl::CapturedContext);
Alexey Bataev9959db52014-05-06 10:08:46 +00004104 DC->addDecl(Param);
4105 CD->setParam(ParamNum, Param);
4106 }
4107 }
4108 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00004109 if (!ContextIsFound) {
4110 // Add __context implicitly if it is not specified.
4111 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4112 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
Alexey Bataev56223232017-06-09 13:40:18 +00004113 auto *Param =
4114 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4115 ImplicitParamDecl::CapturedContext);
Alexey Bataev301a2d92014-05-14 10:40:54 +00004116 DC->addDecl(Param);
4117 CD->setContextParam(ParamNum, Param);
4118 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004119 // Enter the capturing scope for this captured region.
4120 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4121
4122 if (CurScope)
4123 PushDeclContext(CurScope, CD);
4124 else
4125 CurContext = CD;
4126
Faisal Valid143a0c2017-04-01 21:30:49 +00004127 PushExpressionEvaluationContext(
4128 ExpressionEvaluationContext::PotentiallyEvaluated);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004129}
4130
Wei Pan17fbf6e2013-05-04 03:59:06 +00004131void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004132 DiscardCleanupsInEvaluationContext();
4133 PopExpressionEvaluationContext();
4134
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004135 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4136 RecordDecl *Record = RSI->TheRecordDecl;
4137 Record->setInvalidDecl();
4138
Aaron Ballman62e47c42014-03-10 13:43:55 +00004139 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00004140 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4141 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004142
Wei Pan17fbf6e2013-05-04 03:59:06 +00004143 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004144 PopFunctionScopeInfo();
4145}
4146
4147StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4148 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4149
4150 SmallVector<CapturedStmt::Capture, 4> Captures;
4151 SmallVector<Expr *, 4> CaptureInits;
4152 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4153
4154 CapturedDecl *CD = RSI->TheCapturedDecl;
4155 RecordDecl *RD = RSI->TheRecordDecl;
4156
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004157 CapturedStmt *Res = CapturedStmt::Create(
4158 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4159 Captures, CaptureInits, CD, RD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004160
4161 CD->setBody(Res->getCapturedStmt());
4162 RD->completeDefinition();
4163
Wei Pan17fbf6e2013-05-04 03:59:06 +00004164 DiscardCleanupsInEvaluationContext();
4165 PopExpressionEvaluationContext();
4166
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004167 PopDeclContext();
4168 PopFunctionScopeInfo();
4169
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004170 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004171}