blob: 8ca3f5693e2465b65f4d6181b8382334ddb22650 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000016#include "clang/AST/ASTDiagnostic.h"
John McCall03318c12011-11-11 03:57:31 +000017#include "clang/AST/CharUnits.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000018#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Nico Weber72889432014-09-06 01:25:55 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/StmtObjC.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000027#include "clang/AST/TypeOrdering.h"
Reid Kleckner9fe7f232015-07-07 00:36:30 +000028#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000034#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000035#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000036#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000037#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000038#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000039#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000042
Richard Smith945f8d32013-01-14 22:39:08 +000043StmtResult Sema::ActOnExprStmt(ExprResult FE) {
44 if (FE.isInvalid())
45 return StmtError();
46
47 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
48 /*DiscardedValue*/ true);
49 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000050 return StmtError();
51
Chris Lattner903eb512008-07-25 23:18:17 +000052 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
53 // void expression for its side effects. Conversion to void allows any
54 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000055
Chris Lattner903eb512008-07-25 23:18:17 +000056 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000057 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000058}
59
60
John McCalleaef89b2013-03-22 02:10:40 +000061StmtResult Sema::ActOnExprStmtError() {
62 DiscardCleanupsInEvaluationContext();
63 return StmtError();
64}
65
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000066StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000067 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000068 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000069}
70
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000071StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
72 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000073 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000074
Chris Lattnercbafe8d2009-04-12 20:13:14 +000075 // If we have an invalid decl, just return an error.
76 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000077
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000078 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000079}
Chris Lattneraf8d5812006-11-10 05:07:45 +000080
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000081void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000082 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000083
Douglas Gregor2eb1c572013-04-08 20:52:24 +000084 // If we don't have a declaration, or we have an invalid declaration,
85 // just return.
86 if (DG.isNull() || !DG.isSingleDecl())
87 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000088
Douglas Gregor2eb1c572013-04-08 20:52:24 +000089 Decl *decl = DG.getSingleDecl();
90 if (!decl || decl->isInvalidDecl())
91 return;
92
93 // Only variable declarations are permitted.
94 VarDecl *var = dyn_cast<VarDecl>(decl);
95 if (!var) {
96 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
97 decl->setInvalidDecl();
98 return;
99 }
John McCall31168b02011-06-15 23:02:42 +0000100
John McCalld4631322011-06-17 06:42:21 +0000101 // foreach variables are never actually initialized in the way that
102 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000103 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000104
John McCalld4631322011-06-17 06:42:21 +0000105 // In ARC, we don't need to retain the iteration variable of a fast
106 // enumeration loop. Rather than actually trying to catch that
107 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000108 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000109 QualType type = var->getType();
110
111 // Only do this if we inferred the lifetime. Inferred lifetime
112 // will show up as a local qualifier because explicit lifetime
113 // should have shown up as an AttributedType instead.
114 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
115 // Add 'const' and mark the variable as pseudo-strong.
116 var->setType(type.withConst());
117 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000118 }
119 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000120}
121
Richard Trieu99e1c952014-03-11 03:11:08 +0000122/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
123/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000124///
125/// Adding a cast to void (or other expression wrappers) will prevent the
126/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000127static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000128 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000129 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130
131 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000132 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000133 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000134
Richard Trieu99e1c952014-03-11 03:11:08 +0000135 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000136 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000137 IsNotEqual = Op->getOpcode() == BO_NE;
138 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000139 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000140 switch (Op->getOperator()) {
141 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000142 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000143 case OO_EqualEqual:
144 case OO_ExclaimEqual:
145 IsRelational = false;
146 break;
147 case OO_Less:
148 case OO_Greater:
149 case OO_GreaterEqual:
150 case OO_LessEqual:
151 IsRelational = true;
152 break;
153 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000155 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000156 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
157 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000158 } else {
159 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000160 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000161 }
162
163 // Suppress warnings when the operator, suspicious as it may be, comes from
164 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000165 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000166 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000167
Chandler Carruthe2669392011-08-17 09:34:37 +0000168 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000169 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000170
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000171 // If the LHS is a plausible entity to assign to, provide a fixit hint to
172 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000173 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000174 if (IsNotEqual)
175 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
176 << FixItHint::CreateReplacement(Loc, "|=");
177 else
178 S.Diag(Loc, diag::note_equality_comparison_to_assign)
179 << FixItHint::CreateReplacement(Loc, "=");
180 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000181
182 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000183}
184
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000185void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000186 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
187 return DiagnoseUnusedExprResult(Label->getSubStmt());
188
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000189 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000190 if (!E)
191 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000192
193 // If we are in an unevaluated expression context, then there can be no unused
194 // results because the results aren't expected to be used in the first place.
195 if (isUnevaluatedContext())
196 return;
197
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000198 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000199 // In most cases, we don't want to warn if the expression is written in a
200 // macro body, or if the macro comes from a system header. If the offending
201 // expression is a call to a function with the warn_unused_result attribute,
202 // we warn no matter the location. Because of the order in which the various
203 // checks need to happen, we factor out the macro-related test here.
204 bool ShouldSuppress =
205 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
206 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000207
Eli Friedmanc11535c2012-05-24 00:47:05 +0000208 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000209 SourceLocation Loc;
210 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000211 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner6dc7e572012-08-31 22:39:21 +0000214 // If this is a GNU statement expression expanded from a macro, it is probably
215 // unused because it is a function-like macro that can be used as either an
216 // expression or statement. Don't warn, because it is almost certainly a
217 // false positive.
218 if (isa<StmtExpr>(E) && Loc.isMacroID())
219 return;
220
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000221 // Okay, we have an unused result. Depending on what the base expression is,
222 // we might want to make a more specific diagnostic. Check for one of these
223 // cases now.
224 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000225 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000226 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000227 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
228 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000229
Chandler Carruthe2669392011-08-17 09:34:37 +0000230 if (DiagnoseUnusedComparison(*this, E))
231 return;
232
Eli Friedmanc11535c2012-05-24 00:47:05 +0000233 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000234 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000235 if (E->getType()->isVoidType())
236 return;
237
Chris Lattner1a6babf2009-10-13 04:53:48 +0000238 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000239 // a more specific message to make it clear what is happening. If the call
240 // is written in a macro body, only warn if it has the warn_unused_result
241 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000242 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +0000243 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
244 if (Func ? Func->hasUnusedResultAttr()
245 : FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000246 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000247 return;
248 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000249 if (ShouldSuppress)
250 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000251 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000252 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
253 return;
254 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000255 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000256 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
257 return;
258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000260 } else if (ShouldSuppress)
261 return;
262
263 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000264 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000265 Diag(Loc, diag::err_arc_unused_init_message) << R1;
266 return;
267 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000268 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000269 if (MD) {
270 if (MD->hasAttr<WarnUnusedResultAttr>()) {
271 Diag(Loc, diag::warn_unused_result) << R1 << R2;
272 return;
273 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000274 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000275 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
276 const Expr *Source = POE->getSyntacticForm();
277 if (isa<ObjCSubscriptRefExpr>(Source))
278 DiagID = diag::warn_unused_container_subscript_expr;
279 else
280 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000281 } else if (const CXXFunctionalCastExpr *FC
282 = dyn_cast<CXXFunctionalCastExpr>(E)) {
283 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
284 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
285 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000286 }
John McCall2351cb92010-04-06 22:24:14 +0000287 // Diagnose "(void*) blah" as a typo for "(void) blah".
288 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
289 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
290 QualType T = TI->getType();
291
292 // We really do want to use the non-canonical type here.
293 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000294 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000295
296 Diag(Loc, diag::warn_unused_voidptr)
297 << FixItHint::CreateRemoval(TL.getStarLoc());
298 return;
299 }
300 }
301
Eli Friedmanc11535c2012-05-24 00:47:05 +0000302 if (E->isGLValue() && E->getType().isVolatileQualified()) {
303 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
304 return;
305 }
306
Craig Topperc3ec1492014-05-26 06:22:03 +0000307 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000308}
309
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000310void Sema::ActOnStartOfCompoundStmt() {
311 PushCompoundScope();
312}
313
314void Sema::ActOnFinishOfCompoundStmt() {
315 PopCompoundScope();
316}
317
318sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
319 return getCurFunction()->CompoundScopes.back();
320}
321
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000322StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
323 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
324 const unsigned NumElts = Elts.size();
325
Chris Lattnerd864daf2007-08-27 04:29:41 +0000326 // If we're in C89 mode, check that we don't have any decls after stmts. If
327 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000328 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000329 // Note that __extension__ can be around a decl.
330 unsigned i = 0;
331 // Skip over all declarations.
332 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
333 /*empty*/;
334
335 // We found the end of the list or a statement. Scan for another declstmt.
336 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
337 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerd864daf2007-08-27 04:29:41 +0000339 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000340 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000341 Diag(D->getLocation(), diag::ext_mixed_decls_code);
342 }
343 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000344 // Warn about unused expressions in statements.
345 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000346 // Ignore statements that are last in a statement expression.
347 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000348 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000349
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000350 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000351 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000352
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000353 // Check for suspicious empty body (null statement) in `for' and `while'
354 // statements. Don't do anything for template instantiations, this just adds
355 // noise.
356 if (NumElts != 0 && !CurrentInstantiationScope &&
357 getCurCompoundScope().HasEmptyLoopBodies) {
358 for (unsigned i = 0; i != NumElts - 1; ++i)
359 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
360 }
361
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000362 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000363}
364
John McCalldadc5752010-08-24 06:29:42 +0000365StmtResult
John McCallb268a282010-08-23 23:25:46 +0000366Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
367 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000368 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000369 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000370
John McCallaab3e412010-08-25 08:40:02 +0000371 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000372 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000373 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000374 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000375
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000376 ExprResult LHS =
377 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
378 if (!getLangOpts().CPlusPlus11)
379 return VerifyIntegerConstantExpression(E);
380 if (Expr *CondExpr =
381 getCurFunction()->SwitchStack.back()->getCond()) {
382 QualType CondType = CondExpr->getType();
383 llvm::APSInt TempVal;
384 return CheckConvertedConstantExpression(E, CondType, TempVal,
385 CCEK_CaseValue);
386 }
387 return ExprError();
388 });
389 if (LHS.isInvalid())
390 return StmtError();
391 LHSVal = LHS.get();
392
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000393 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000394 // C99 6.8.4.2p3: The expression shall be an integer constant.
395 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000396 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000397 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000398 if (!LHSVal)
399 return StmtError();
400 }
Richard Smithf8379a02012-01-18 23:55:52 +0000401
402 // GCC extension: The expression shall be an integer constant.
403
Richard Smithf4c51d92012-02-04 09:53:13 +0000404 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000405 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000406 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000407 }
408 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000409
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000410 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000411 getLangOpts().CPlusPlus11);
412 if (LHS.isInvalid())
413 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000414
Richard Smith5b555da2014-11-20 01:24:12 +0000415 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
416 getLangOpts().CPlusPlus11)
417 : ExprResult();
418 if (RHS.isInvalid())
419 return StmtError();
420
421 CaseStmt *CS = new (Context)
422 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000423 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000424 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000425}
426
Chris Lattner34a22092009-03-04 04:23:07 +0000427/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000428void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000429 DiagnoseUnusedExprResult(SubStmt);
430
Chris Lattner34a22092009-03-04 04:23:07 +0000431 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000432 CS->setSubStmt(SubStmt);
433}
434
John McCalldadc5752010-08-24 06:29:42 +0000435StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000436Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000437 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000438 DiagnoseUnusedExprResult(SubStmt);
439
John McCallaab3e412010-08-25 08:40:02 +0000440 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000441 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000442 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000443 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000444
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000445 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000446 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000447 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000448}
449
John McCalldadc5752010-08-24 06:29:42 +0000450StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000451Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
452 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000453 // If the label was multiply defined, reject it now.
454 if (TheDecl->getStmt()) {
455 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
456 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000458 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000459
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000460 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000461 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
462 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000463 if (!TheDecl->isGnuLocal()) {
464 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000465 if (!TheDecl->isMSAsmLabel()) {
466 // Don't update the location of MS ASM labels. These will result in
467 // a diagnostic, and changing the location here will mess that up.
468 TheDecl->setLocation(IdentLoc);
469 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000470 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000471 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000472}
473
Richard Smithc202b282012-04-14 00:33:13 +0000474StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000475 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000476 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000477 // Fill in the declaration and return it.
478 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000479 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000480}
481
John McCalldadc5752010-08-24 06:29:42 +0000482StmtResult
John McCall48871652010-08-21 09:40:31 +0000483Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000484 Stmt *thenStmt, SourceLocation ElseLoc,
485 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000486 // If the condition was invalid, discard the if statement. We could recover
487 // better by replacing it with a valid expr, but don't do that yet.
488 if (!CondVal.get() && !CondVar) {
489 getCurFunction()->setHasDroppedStmt();
490 return StmtError();
491 }
492
John McCalldadc5752010-08-24 06:29:42 +0000493 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000494
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000496 if (CondVar) {
497 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000498 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +0000499 CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000500 if (CondResult.isInvalid())
501 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000502 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000503 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000504 if (!ConditionExpr)
505 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000507 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000508
John McCallb268a282010-08-23 23:25:46 +0000509 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000510 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
511 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000512 }
513
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000514 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000515
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000516 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
517 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000518}
Steve Naroff86272ea2007-05-29 02:14:17 +0000519
Chris Lattner67998452007-08-23 18:29:20 +0000520namespace {
521 struct CaseCompareFunctor {
522 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
523 const llvm::APSInt &RHS) {
524 return LHS.first < RHS;
525 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000526 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
527 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
528 return LHS.first < RHS.first;
529 }
Chris Lattner67998452007-08-23 18:29:20 +0000530 bool operator()(const llvm::APSInt &LHS,
531 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
532 return LHS < RHS.first;
533 }
534 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000535}
Chris Lattner67998452007-08-23 18:29:20 +0000536
Chris Lattner4b2ff022007-09-21 18:15:22 +0000537/// CmpCaseVals - Comparison predicate for sorting case values.
538///
539static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
540 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
541 if (lhs.first < rhs.first)
542 return true;
543
544 if (lhs.first == rhs.first &&
545 lhs.second->getCaseLoc().getRawEncoding()
546 < rhs.second->getCaseLoc().getRawEncoding())
547 return true;
548 return false;
549}
550
Douglas Gregorbd6839732010-02-08 22:24:16 +0000551/// CmpEnumVals - Comparison predicate for sorting enumeration values.
552///
553static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
554 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
555{
556 return lhs.first < rhs.first;
557}
558
559/// EqEnumVals - Comparison preficate for uniqing enumeration values.
560///
561static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
562 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
563{
564 return lhs.first == rhs.first;
565}
566
Chris Lattnera96d4272009-10-16 16:45:22 +0000567/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
568/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000569static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
570 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
571 expr = cleanups->getSubExpr();
572 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
573 if (impcast->getCastKind() != CK_IntegralCast) break;
574 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000575 }
576 return expr->getType();
577}
578
John McCalldadc5752010-08-24 06:29:42 +0000579StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000581 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000582 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000583
Craig Topperc3ec1492014-05-26 06:22:03 +0000584 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000585 if (CondVar) {
586 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000587 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
588 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000589 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000591 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
John McCallb268a282010-08-23 23:25:46 +0000594 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000595 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596
Douglas Gregore2b37442012-05-04 22:38:52 +0000597 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
598 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000599
Douglas Gregore2b37442012-05-04 22:38:52 +0000600 public:
601 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000602 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
603 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000604
Craig Toppere14c0f82014-03-12 04:55:44 +0000605 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
606 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000607 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
608 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000609
Craig Toppere14c0f82014-03-12 04:55:44 +0000610 SemaDiagnosticBuilder diagnoseIncomplete(
611 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000612 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
613 << T << Cond->getSourceRange();
614 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000615
Craig Toppere14c0f82014-03-12 04:55:44 +0000616 SemaDiagnosticBuilder diagnoseExplicitConv(
617 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000618 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
619 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000620
Craig Toppere14c0f82014-03-12 04:55:44 +0000621 SemaDiagnosticBuilder noteExplicitConv(
622 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000623 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
624 << ConvTy->isEnumeralType() << ConvTy;
625 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000626
Craig Toppere14c0f82014-03-12 04:55:44 +0000627 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
628 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000629 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
630 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000631
Craig Toppere14c0f82014-03-12 04:55:44 +0000632 SemaDiagnosticBuilder noteAmbiguous(
633 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000634 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
635 << ConvTy->isEnumeralType() << ConvTy;
636 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000637
Craig Toppere14c0f82014-03-12 04:55:44 +0000638 SemaDiagnosticBuilder diagnoseConversion(
639 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000640 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000641 }
642 } SwitchDiagnoser(Cond);
643
Richard Smithccc11812013-05-21 19:05:48 +0000644 CondResult =
645 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000646 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000647 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000648
John McCall5939b162011-08-06 07:30:58 +0000649 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
650 CondResult = UsualUnaryConversions(Cond);
651 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000652 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000653
Meador Ingef0af05c2015-06-25 22:06:40 +0000654 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
655 if (CondResult.isInvalid())
656 return StmtError();
657 Cond = CondResult.get();
John McCalla95172b2010-08-01 00:26:45 +0000658
John McCallaab3e412010-08-25 08:40:02 +0000659 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660
John McCallb268a282010-08-23 23:25:46 +0000661 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000662 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000663 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000664}
665
Gabor Greif16e02862010-10-01 22:05:14 +0000666static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000667 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000668 Val.setIsSigned(IsSigned);
669}
670
Richard Smith077d0832014-08-04 00:40:48 +0000671/// Check the specified case value is in range for the given unpromoted switch
672/// type.
673static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
674 unsigned UnpromotedWidth, bool UnpromotedSign) {
675 // If the case value was signed and negative and the switch expression is
676 // unsigned, don't bother to warn: this is implementation-defined behavior.
677 // FIXME: Introduce a second, default-ignored warning for this case?
678 if (UnpromotedWidth < Val.getBitWidth()) {
679 llvm::APSInt ConvVal(Val);
680 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
681 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
682 // FIXME: Use different diagnostics for overflow in conversion to promoted
683 // type versus "switch expression cannot have this value". Use proper
684 // IntRange checking rather than just looking at the unpromoted type here.
685 if (ConvVal != Val)
686 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
687 << ConvVal.toString(10);
688 }
689}
690
Alexis Hunt724f14e2014-11-28 00:53:20 +0000691typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
692
Dmitri Gribenko58683752013-12-05 22:52:07 +0000693/// Returns true if we should emit a diagnostic about this case expression not
694/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000695static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000696 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000697 const Expr *CaseExpr,
698 EnumValsTy::iterator &EI,
699 EnumValsTy::iterator &EIEnd,
700 const llvm::APSInt &Val) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000701 if (const DeclRefExpr *DRE =
702 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000703 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Dmitri Gribenko58683752013-12-05 22:52:07 +0000704 QualType VarType = VD->getType();
Alexis Hunt724f14e2014-11-28 00:53:20 +0000705 QualType EnumType = S.Context.getTypeDeclType(ED);
706 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
707 S.Context.hasSameUnqualifiedType(EnumType, VarType))
Dmitri Gribenko58683752013-12-05 22:52:07 +0000708 return false;
709 }
710 }
Alexis Hunt724f14e2014-11-28 00:53:20 +0000711
Richard Smith332653c2015-09-04 01:03:03 +0000712 if (ED->hasAttr<FlagEnumAttr>()) {
Alexis Hunt724f14e2014-11-28 00:53:20 +0000713 return !S.IsValueInFlagEnum(ED, Val, false);
714 } else {
715 while (EI != EIEnd && EI->first < Val)
716 EI++;
717
718 if (EI != EIEnd && EI->first == Val)
719 return false;
720 }
721
Dmitri Gribenko58683752013-12-05 22:52:07 +0000722 return true;
723}
724
John McCalldadc5752010-08-24 06:29:42 +0000725StmtResult
John McCallb268a282010-08-23 23:25:46 +0000726Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
727 Stmt *BodyStmt) {
728 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000729 assert(SS == getCurFunction()->SwitchStack.back() &&
730 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000731
David Majnemer418ad3f2014-12-15 07:46:12 +0000732 getCurFunction()->SwitchStack.pop_back();
733
Serge Pavlov921c2ba2014-05-21 14:48:43 +0000734 if (!BodyStmt) return StmtError();
Steve Naroff42a350a2007-09-01 21:08:38 +0000735 SS->setBody(BodyStmt, SwitchLoc);
Anders Carlsson51873c22007-07-22 07:07:56 +0000736
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000737 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000738 if (!CondExpr) return StmtError();
739
740 QualType CondType = CondExpr->getType();
741
John McCalld3dfbd62010-05-18 03:19:21 +0000742 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000743 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000744 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000745
Chris Lattnera96d4272009-10-16 16:45:22 +0000746 // C++ 6.4.2.p2:
747 // Integral promotions are performed (on the switch condition).
748 //
749 // A case value unrepresentable by the original switch condition
750 // type (before the promotion) doesn't make sense, even when it can
751 // be represented by the promoted type. Therefore we need to find
752 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000753 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000754 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000755 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000756 // appropriate type now, just return an error.
757 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000758 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000759
Chris Lattner4ebae652010-04-16 23:34:13 +0000760 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000761 // switch(bool_expr) {...} is often a programmer error, e.g.
762 // switch(n && mask) { ... } // Doh - should be "n & mask".
763 // One can always use an if statement instead of switch(bool_expr).
764 Diag(SwitchLoc, diag::warn_bool_switch_condition)
765 << CondExpr->getSourceRange();
766 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000767 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000768
Richard Smith077d0832014-08-04 00:40:48 +0000769 // Get the bitwidth of the switched-on value after promotions. We must
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000770 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000771 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000772 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Richard Smith077d0832014-08-04 00:40:48 +0000773 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
774 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
775
776 // Get the width and signedness that the condition might actually have, for
777 // warning purposes.
778 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
779 // type.
780 unsigned CondWidthBeforePromotion
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000781 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Richard Smith077d0832014-08-04 00:40:48 +0000782 bool CondIsSignedBeforePromotion
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000783 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000785 // Accumulate all of the case values in a vector so that we can sort them
786 // and detect duplicates. This vector contains the APInt for the case after
787 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000788 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000789 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000791 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000792 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
793 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000794
Craig Topperc3ec1492014-05-26 06:22:03 +0000795 DefaultStmt *TheDefaultStmt = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattner10cb5e52007-08-23 06:23:56 +0000797 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000799 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000800 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000801
Anders Carlsson51873c22007-07-22 07:07:56 +0000802 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000803 if (TheDefaultStmt) {
804 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000805 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000806
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000807 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000808 // we'll return a valid AST. This requires recursing down the AST and
809 // finding it, not something we are set up to do right now. For now,
810 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000811 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000812 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000813 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000814
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000815 } else {
816 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000817
Chris Lattnera65e1f32008-01-16 19:17:22 +0000818 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000819
820 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
821 HasDependentValue = true;
822 break;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Richard Smithf8379a02012-01-18 23:55:52 +0000825 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000826
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000827 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000828 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
829 // constant expression of the promoted type of the switch condition.
830 ExprResult ConvLo =
831 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
832 if (ConvLo.isInvalid()) {
833 CaseListIsErroneous = true;
834 continue;
835 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000836 Lo = ConvLo.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000837 } else {
838 // We already verified that the expression has a i-c-e value (C99
839 // 6.8.4.2p3) - get that value now.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000840 LoVal = Lo->EvaluateKnownConstInt(Context);
Richard Smithf8379a02012-01-18 23:55:52 +0000841
842 // If the LHS is not the same type as the condition, insert an implicit
843 // cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000844 Lo = DefaultLvalueConversion(Lo).get();
845 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000846 }
847
Richard Smith077d0832014-08-04 00:40:48 +0000848 // Check the unconverted value is within the range of possible values of
849 // the switch expression.
850 checkCaseValue(*this, Lo->getLocStart(), LoVal,
851 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
852
853 // Convert the value to the same width/sign as the condition.
854 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
Anders Carlsson51873c22007-07-22 07:07:56 +0000855
Chris Lattnera65e1f32008-01-16 19:17:22 +0000856 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000857
Chris Lattner10cb5e52007-08-23 06:23:56 +0000858 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000859 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000860 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000861 CS->getRHS()->isValueDependent()) {
862 HasDependentValue = true;
863 break;
864 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000865 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000866 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000867 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000868 }
869 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000870
871 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000872 // If we don't have a default statement, check whether the
873 // condition is constant.
874 llvm::APSInt ConstantCondValue;
875 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000876 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith077d0832014-08-04 00:40:48 +0000877 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
878 Expr::SE_AllowSideEffects);
Richard Smith5fab0c92011-12-28 19:48:30 +0000879 assert(!HasConstantCond ||
880 (ConstantCondValue.getBitWidth() == CondWidth &&
881 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000882 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000883 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000884
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000885 // Sort all the scalar case values so we can easily detect duplicates.
886 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
887
888 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000889 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
890 if (ShouldCheckConstantCond &&
891 CaseVals[i].first == ConstantCondValue)
892 ShouldCheckConstantCond = false;
893
894 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000895 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000896 // First, determine if either case value has a name
897 StringRef PrevString, CurrString;
898 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
899 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
900 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
901 PrevString = DeclRef->getDecl()->getName();
902 }
903 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
904 CurrString = DeclRef->getDecl()->getName();
905 }
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000906 SmallString<16> CaseValStr;
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000907 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000908
909 if (PrevString == CurrString)
910 Diag(CaseVals[i].second->getLHS()->getLocStart(),
911 diag::err_duplicate_case) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000912 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000913 else
914 Diag(CaseVals[i].second->getLHS()->getLocStart(),
915 diag::err_duplicate_case_differing_expr) <<
Yaron Keren49c63692015-03-18 10:26:22 +0000916 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
917 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000918 CaseValStr;
919
John McCalld3dfbd62010-05-18 03:19:21 +0000920 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000921 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000922 // FIXME: We really want to remove the bogus case stmt from the
923 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000924 CaseListIsErroneous = true;
925 }
926 }
927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000929 // Detect duplicate case ranges, which usually don't exist at all in
930 // the first place.
931 if (!CaseRanges.empty()) {
932 // Sort all the case ranges by their low value so we can easily detect
933 // overlaps between ranges.
934 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000935
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000936 // Scan the ranges, computing the high values and removing empty ranges.
937 std::vector<llvm::APSInt> HiVals;
938 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000939 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000940 CaseStmt *CR = CaseRanges[i].second;
941 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000942 llvm::APSInt HiVal;
943
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000944 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000945 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
946 // constant expression of the promoted type of the switch condition.
947 ExprResult ConvHi =
948 CheckConvertedConstantExpression(Hi, CondType, HiVal,
949 CCEK_CaseValue);
950 if (ConvHi.isInvalid()) {
951 CaseListIsErroneous = true;
952 continue;
953 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000954 Hi = ConvHi.get();
Richard Smithf8379a02012-01-18 23:55:52 +0000955 } else {
956 HiVal = Hi->EvaluateKnownConstInt(Context);
957
958 // If the RHS is not the same type as the condition, insert an
959 // implicit cast.
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000960 Hi = DefaultLvalueConversion(Hi).get();
961 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
Richard Smithf8379a02012-01-18 23:55:52 +0000962 }
Mike Stump11289f42009-09-09 15:08:12 +0000963
Richard Smith077d0832014-08-04 00:40:48 +0000964 // Check the unconverted value is within the range of possible values of
965 // the switch expression.
966 checkCaseValue(*this, Hi->getLocStart(), HiVal,
967 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
968
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000969 // Convert the value to the same width/sign as the condition.
Richard Smith077d0832014-08-04 00:40:48 +0000970 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
Mike Stump11289f42009-09-09 15:08:12 +0000971
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000972 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000973
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000974 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000975 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000976 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
977 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000978 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000979 CaseRanges.erase(CaseRanges.begin()+i);
980 --i, --e;
981 continue;
982 }
John McCalld3dfbd62010-05-18 03:19:21 +0000983
984 if (ShouldCheckConstantCond &&
985 LoVal <= ConstantCondValue &&
986 ConstantCondValue <= HiVal)
987 ShouldCheckConstantCond = false;
988
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000989 HiVals.push_back(HiVal);
990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000992 // Rescan the ranges, looking for overlap with singleton values and other
993 // ranges. Since the range list is sorted, we only need to compare case
994 // ranges with their neighbors.
995 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
996 llvm::APSInt &CRLo = CaseRanges[i].first;
997 llvm::APSInt &CRHi = HiVals[i];
998 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000999
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001000 // Check to see whether the case range overlaps with any
1001 // singleton cases.
Craig Topperc3ec1492014-05-26 06:22:03 +00001002 CaseStmt *OverlapStmt = nullptr;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001003 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001005 // Find the smallest value >= the lower bound. If I is in the
1006 // case range, then we have overlap.
1007 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1008 CaseVals.end(), CRLo,
1009 CaseCompareFunctor());
1010 if (I != CaseVals.end() && I->first < CRHi) {
1011 OverlapVal = I->first; // Found overlap with scalar.
1012 OverlapStmt = I->second;
1013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001015 // Find the smallest value bigger than the upper bound.
1016 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1017 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1018 OverlapVal = (I-1)->first; // Found overlap with scalar.
1019 OverlapStmt = (I-1)->second;
1020 }
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001022 // Check to see if this case stmt overlaps with the subsequent
1023 // case range.
1024 if (i && CRLo <= HiVals[i-1]) {
1025 OverlapVal = HiVals[i-1]; // Found overlap with range.
1026 OverlapStmt = CaseRanges[i-1].second;
1027 }
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001029 if (OverlapStmt) {
1030 // If we have a duplicate, report it.
1031 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1032 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +00001033 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001034 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +00001035 // FIXME: We really want to remove the bogus case stmt from the
1036 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +00001037 CaseListIsErroneous = true;
1038 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +00001039 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001040 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001041
John McCalld3dfbd62010-05-18 03:19:21 +00001042 // Complain if we have a constant condition and we didn't find a match.
1043 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1044 // TODO: it would be nice if we printed enums as enums, chars as
1045 // chars, etc.
1046 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1047 << ConstantCondValue.toString(10)
1048 << CondExpr->getSourceRange();
1049 }
1050
1051 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +00001052 // values. We only issue a warning if there is not 'default:', but
1053 // we still do the analysis to preserve this information in the AST
1054 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +00001055 //
Chris Lattner51679082010-09-16 17:09:42 +00001056 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001057
Douglas Gregorbd6839732010-02-08 22:24:16 +00001058 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +00001059 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +00001060 const EnumDecl *ED = ET->getDecl();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001061 EnumValsTy EnumVals;
1062
John McCalld3dfbd62010-05-18 03:19:21 +00001063 // Gather all enum values, set their type and sort them,
1064 // allowing easier comparison with CaseVals.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001065 for (auto *EDI : ED->enumerators()) {
Gabor Greif16e02862010-10-01 22:05:14 +00001066 llvm::APSInt Val = EDI->getInitVal();
1067 AdjustAPSInt(Val, CondWidth, CondIsSigned);
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001068 EnumVals.push_back(std::make_pair(Val, EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +00001069 }
1070 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001071 auto EI = EnumVals.begin(), EIEnd =
John McCalld3dfbd62010-05-18 03:19:21 +00001072 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +00001073
1074 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +00001075 for (CaseValsTy::const_iterator CI = CaseVals.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001076 CI != CaseVals.end(); CI++) {
1077 Expr *CaseExpr = CI->second->getLHS();
1078 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1079 CI->first))
1080 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1081 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001082 }
Alexis Hunt724f14e2014-11-28 00:53:20 +00001083
David Blaikiee476f972012-01-22 02:31:55 +00001084 // See which of case ranges aren't in enum
1085 EI = EnumVals.begin();
1086 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001087 RI != CaseRanges.end(); RI++) {
1088 Expr *CaseExpr = RI->second->getLHS();
1089 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1090 RI->first))
1091 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1092 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +00001093
Chad Rosier02a84392012-08-10 17:56:09 +00001094 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +00001095 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1096 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Alexis Hunt724f14e2014-11-28 00:53:20 +00001097
1098 CaseExpr = RI->second->getRHS();
1099 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1100 Hi))
1101 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1102 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
Ted Kremenekc42f3452010-09-09 00:05:53 +00001105 // Check which enum vals aren't in switch
Alexis Hunt724f14e2014-11-28 00:53:20 +00001106 auto CI = CaseVals.begin();
1107 auto RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001108 bool hasCasesNotInSwitch = false;
1109
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001110 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Alexis Hunt724f14e2014-11-28 00:53:20 +00001112 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001113 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001114 while (CI != CaseVals.end() && CI->first < EI->first)
1115 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001116
Douglas Gregorbd6839732010-02-08 22:24:16 +00001117 if (CI != CaseVals.end() && CI->first == EI->first)
1118 continue;
1119
Ted Kremenekc42f3452010-09-09 00:05:53 +00001120 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001121 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001122 llvm::APSInt Hi =
1123 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001124 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001125 if (EI->first <= Hi)
1126 break;
1127 }
1128
Ted Kremenekc42f3452010-09-09 00:05:53 +00001129 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001130 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001131 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001132 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134
David Blaikie60ac6382012-01-23 04:46:12 +00001135 if (TheDefaultStmt && UnhandledNames.empty())
1136 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001137
Chris Lattner51679082010-09-16 17:09:42 +00001138 // Produce a nice diagnostic if multiple values aren't handled.
Benjamin Kramer3a8650a2015-03-27 17:23:14 +00001139 if (!UnhandledNames.empty()) {
1140 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1141 TheDefaultStmt ? diag::warn_def_missing_case
1142 : diag::warn_missing_case)
1143 << (int)UnhandledNames.size();
1144
1145 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1146 I != E; ++I)
1147 DB << UnhandledNames[I];
Chris Lattner51679082010-09-16 17:09:42 +00001148 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001149
1150 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001151 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001152 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001153 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001154
Serge Pavlov921c2ba2014-05-21 14:48:43 +00001155 if (BodyStmt)
1156 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1157 diag::warn_empty_switch_body);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001158
Mike Stump87c57ac2009-05-16 07:39:55 +00001159 // FIXME: If the case list was broken is some way, we don't have a good system
1160 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001161 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001162 return StmtError();
1163
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001164 return SS;
Chris Lattneraf8d5812006-11-10 05:07:45 +00001165}
1166
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001167void
1168Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1169 Expr *SrcExpr) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001170 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001171 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001172
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001173 if (const EnumType *ET = DstType->getAs<EnumType>())
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001174 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001175 SrcType->isIntegerType()) {
1176 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1177 SrcExpr->isIntegerConstantExpr(Context)) {
1178 // Get the bitwidth of the enum value before promotions.
Joey Gouly1ba27332013-06-06 13:48:00 +00001179 unsigned DstWidth = Context.getIntWidth(DstType);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001180 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1181
1182 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
Joey Gouly1ba27332013-06-06 13:48:00 +00001183 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001184 const EnumDecl *ED = ET->getDecl();
Chad Rosier02a84392012-08-10 17:56:09 +00001185
Alexis Hunt724f14e2014-11-28 00:53:20 +00001186 if (ED->hasAttr<FlagEnumAttr>()) {
1187 if (!IsValueInFlagEnum(ED, RhsVal, true))
1188 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
Dmitri Gribenkoe6ac50a2013-12-05 23:06:53 +00001189 << DstType.getUnqualifiedType();
Alexis Hunt724f14e2014-11-28 00:53:20 +00001190 } else {
1191 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1192 EnumValsTy;
1193 EnumValsTy EnumVals;
1194
1195 // Gather all enum values, set their type and sort them,
1196 // allowing easier comparison with rhs constant.
1197 for (auto *EDI : ED->enumerators()) {
1198 llvm::APSInt Val = EDI->getInitVal();
1199 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1200 EnumVals.push_back(std::make_pair(Val, EDI));
1201 }
1202 if (EnumVals.empty())
1203 return;
1204 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1205 EnumValsTy::iterator EIend =
1206 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1207
1208 // See which values aren't in the enum.
1209 EnumValsTy::const_iterator EI = EnumVals.begin();
1210 while (EI != EIend && EI->first < RhsVal)
1211 EI++;
1212 if (EI == EIend || EI->first != RhsVal) {
1213 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1214 << DstType.getUnqualifiedType();
1215 }
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001216 }
1217 }
1218 }
1219}
1220
John McCalldadc5752010-08-24 06:29:42 +00001221StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001222Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001223 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001224 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
Craig Topperc3ec1492014-05-26 06:22:03 +00001226 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001227 if (CondVar) {
1228 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001229 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001230 CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001231 if (CondResult.isInvalid())
1232 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001233 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001234 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001235 if (!ConditionExpr)
1236 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001237 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238
John McCallb268a282010-08-23 23:25:46 +00001239 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001241 if (isa<NullStmt>(Body))
1242 getCurCompoundScope().setHasEmptyLoopBodies();
1243
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001244 return new (Context)
1245 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001246}
1247
John McCalldadc5752010-08-24 06:29:42 +00001248StmtResult
John McCallb268a282010-08-23 23:25:46 +00001249Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001250 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001251 Expr *Cond, SourceLocation CondRParen) {
1252 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001253
Serge Pavlov09f99242014-01-23 15:05:00 +00001254 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001255 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001256 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001257 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001258 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001259
Richard Smith945f8d32013-01-14 22:39:08 +00001260 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001261 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001262 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001263 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
John McCallb268a282010-08-23 23:25:46 +00001265 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001266
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001267 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001268}
1269
Richard Trieu451a5db2012-04-30 18:01:30 +00001270namespace {
1271 // This visitor will traverse a conditional statement and store all
1272 // the evaluated decls into a vector. Simple is set to true if none
1273 // of the excluded constructs are used.
1274 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001275 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001276 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001277 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001278 public:
1279 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001280
Craig Topper4dd9b432014-08-17 23:49:53 +00001281 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001282 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001283 Inherited(S.Context),
1284 Decls(Decls),
1285 Ranges(Ranges),
1286 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001287
Richard Trieu9d228802013-05-31 22:46:45 +00001288 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001289
Richard Trieu9d228802013-05-31 22:46:45 +00001290 // Replaces the method in EvaluatedExprVisitor.
1291 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001292 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001293 }
1294
1295 // Any Stmt not whitelisted will cause the condition to be marked complex.
1296 void VisitStmt(Stmt *S) {
1297 Simple = false;
1298 }
1299
1300 void VisitBinaryOperator(BinaryOperator *E) {
1301 Visit(E->getLHS());
1302 Visit(E->getRHS());
1303 }
1304
1305 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001306 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001307 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001308
Richard Trieu9d228802013-05-31 22:46:45 +00001309 void VisitUnaryOperator(UnaryOperator *E) {
1310 // Skip checking conditionals with derefernces.
1311 if (E->getOpcode() == UO_Deref)
1312 Simple = false;
1313 else
1314 Visit(E->getSubExpr());
1315 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001316
Richard Trieu9d228802013-05-31 22:46:45 +00001317 void VisitConditionalOperator(ConditionalOperator *E) {
1318 Visit(E->getCond());
1319 Visit(E->getTrueExpr());
1320 Visit(E->getFalseExpr());
1321 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001322
Richard Trieu9d228802013-05-31 22:46:45 +00001323 void VisitParenExpr(ParenExpr *E) {
1324 Visit(E->getSubExpr());
1325 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001326
Richard Trieu9d228802013-05-31 22:46:45 +00001327 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1328 Visit(E->getOpaqueValue()->getSourceExpr());
1329 Visit(E->getFalseExpr());
1330 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001331
Richard Trieu9d228802013-05-31 22:46:45 +00001332 void VisitIntegerLiteral(IntegerLiteral *E) { }
1333 void VisitFloatingLiteral(FloatingLiteral *E) { }
1334 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1335 void VisitCharacterLiteral(CharacterLiteral *E) { }
1336 void VisitGNUNullExpr(GNUNullExpr *E) { }
1337 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001338
Richard Trieu9d228802013-05-31 22:46:45 +00001339 void VisitDeclRefExpr(DeclRefExpr *E) {
1340 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1341 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001342
Richard Trieu9d228802013-05-31 22:46:45 +00001343 Ranges.push_back(E->getSourceRange());
1344
1345 Decls.insert(VD);
1346 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001347
1348 }; // end class DeclExtractor
1349
Sanjay Patel69e7f6e2015-08-28 14:42:54 +00001350 // DeclMatcher checks to see if the decls are used in a non-evaluated
Chad Rosier02a84392012-08-10 17:56:09 +00001351 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001352 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001353 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001354 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001355
Richard Trieu9d228802013-05-31 22:46:45 +00001356 public:
1357 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001358
Craig Topper4dd9b432014-08-17 23:49:53 +00001359 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001360 Stmt *Statement) :
1361 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1362 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001363
Richard Trieu9d228802013-05-31 22:46:45 +00001364 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001365 }
1366
Richard Trieu9d228802013-05-31 22:46:45 +00001367 void VisitReturnStmt(ReturnStmt *S) {
1368 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001369 }
1370
Richard Trieu9d228802013-05-31 22:46:45 +00001371 void VisitBreakStmt(BreakStmt *S) {
1372 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001373 }
1374
Richard Trieu9d228802013-05-31 22:46:45 +00001375 void VisitGotoStmt(GotoStmt *S) {
1376 FoundDecl = true;
1377 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001378
Richard Trieu9d228802013-05-31 22:46:45 +00001379 void VisitCastExpr(CastExpr *E) {
1380 if (E->getCastKind() == CK_LValueToRValue)
1381 CheckLValueToRValueCast(E->getSubExpr());
1382 else
1383 Visit(E->getSubExpr());
1384 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001385
Richard Trieu9d228802013-05-31 22:46:45 +00001386 void CheckLValueToRValueCast(Expr *E) {
1387 E = E->IgnoreParenImpCasts();
1388
1389 if (isa<DeclRefExpr>(E)) {
1390 return;
1391 }
1392
1393 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1394 Visit(CO->getCond());
1395 CheckLValueToRValueCast(CO->getTrueExpr());
1396 CheckLValueToRValueCast(CO->getFalseExpr());
1397 return;
1398 }
1399
1400 if (BinaryConditionalOperator *BCO =
1401 dyn_cast<BinaryConditionalOperator>(E)) {
1402 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1403 CheckLValueToRValueCast(BCO->getFalseExpr());
1404 return;
1405 }
1406
1407 Visit(E);
1408 }
1409
1410 void VisitDeclRefExpr(DeclRefExpr *E) {
1411 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1412 if (Decls.count(VD))
1413 FoundDecl = true;
1414 }
1415
1416 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001417
1418 }; // end class DeclMatcher
1419
1420 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1421 Expr *Third, Stmt *Body) {
1422 // Condition is empty
1423 if (!Second) return;
1424
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001425 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1426 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001427 return;
1428
1429 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1430 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001431 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001432 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001433 DE.Visit(Second);
1434
1435 // Don't analyze complex conditionals.
1436 if (!DE.isSimple()) return;
1437
1438 // No decls found.
1439 if (Decls.size() == 0) return;
1440
Richard Trieu0030f1d2012-05-04 03:01:54 +00001441 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001442 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1443 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001444 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001445 if ((*I)->getType().isVolatileQualified() ||
1446 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001447
1448 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1449 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1450 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1451 return;
1452
1453 // Load decl names into diagnostic.
1454 if (Decls.size() > 4)
1455 PDiag << 0;
1456 else {
1457 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001458 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1459 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001460 I != E; ++I)
1461 PDiag << (*I)->getDeclName();
1462 }
1463
1464 // Load SourceRanges into diagnostic if there is room.
1465 // Otherwise, load the SourceRange of the conditional expression.
1466 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001467 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001468 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001469 I != E; ++I)
1470 PDiag << *I;
1471 else
1472 PDiag << Second->getSourceRange();
1473
1474 S.Diag(Ranges.begin()->getBegin(), PDiag);
1475 }
1476
Richard Trieu4e7c9622013-08-06 21:31:54 +00001477 // If Statement is an incemement or decrement, return true and sets the
1478 // variables Increment and DRE.
1479 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1480 DeclRefExpr *&DRE) {
1481 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1482 switch (UO->getOpcode()) {
1483 default: return false;
1484 case UO_PostInc:
1485 case UO_PreInc:
1486 Increment = true;
1487 break;
1488 case UO_PostDec:
1489 case UO_PreDec:
1490 Increment = false;
1491 break;
1492 }
1493 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1494 return DRE;
1495 }
1496
1497 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1498 FunctionDecl *FD = Call->getDirectCallee();
1499 if (!FD || !FD->isOverloadedOperator()) return false;
1500 switch (FD->getOverloadedOperator()) {
1501 default: return false;
1502 case OO_PlusPlus:
1503 Increment = true;
1504 break;
1505 case OO_MinusMinus:
1506 Increment = false;
1507 break;
1508 }
1509 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1510 return DRE;
1511 }
1512
1513 return false;
1514 }
1515
Serge Pavlov09f99242014-01-23 15:05:00 +00001516 // A visitor to determine if a continue or break statement is a
1517 // subexpression.
1518 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1519 SourceLocation BreakLoc;
1520 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001521 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001522 BreakContinueFinder(Sema &S, Stmt* Body) :
1523 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001524 Visit(Body);
1525 }
1526
Serge Pavlov09f99242014-01-23 15:05:00 +00001527 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001528
1529 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001530 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001531 }
1532
Serge Pavlov09f99242014-01-23 15:05:00 +00001533 void VisitBreakStmt(BreakStmt* E) {
1534 BreakLoc = E->getBreakLoc();
1535 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001536
Serge Pavlov09f99242014-01-23 15:05:00 +00001537 bool ContinueFound() { return ContinueLoc.isValid(); }
1538 bool BreakFound() { return BreakLoc.isValid(); }
1539 SourceLocation GetContinueLoc() { return ContinueLoc; }
1540 SourceLocation GetBreakLoc() { return BreakLoc; }
1541
1542 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001543
1544 // Emit a warning when a loop increment/decrement appears twice per loop
1545 // iteration. The conditions which trigger this warning are:
1546 // 1) The last statement in the loop body and the third expression in the
1547 // for loop are both increment or both decrement of the same variable
1548 // 2) No continue statements in the loop body.
1549 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1550 // Return when there is nothing to check.
1551 if (!Body || !Third) return;
1552
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001553 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1554 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001555 return;
1556
1557 // Get the last statement from the loop body.
1558 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1559 if (!CS || CS->body_empty()) return;
1560 Stmt *LastStmt = CS->body_back();
1561 if (!LastStmt) return;
1562
1563 bool LoopIncrement, LastIncrement;
1564 DeclRefExpr *LoopDRE, *LastDRE;
1565
1566 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1567 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1568
1569 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001570 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001571 if (LoopIncrement != LastIncrement ||
1572 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1573
Serge Pavlov09f99242014-01-23 15:05:00 +00001574 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001575
1576 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1577 << LastDRE->getDecl() << LastIncrement;
1578 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1579 << LoopIncrement;
1580 }
1581
Richard Trieu451a5db2012-04-30 18:01:30 +00001582} // end namespace
1583
Serge Pavlov09f99242014-01-23 15:05:00 +00001584
1585void Sema::CheckBreakContinueBinding(Expr *E) {
1586 if (!E || getLangOpts().CPlusPlus)
1587 return;
1588 BreakContinueFinder BCFinder(*this, E);
1589 Scope *BreakParent = CurScope->getBreakParent();
1590 if (BCFinder.BreakFound() && BreakParent) {
1591 if (BreakParent->getFlags() & Scope::SwitchScope) {
1592 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1593 } else {
1594 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1595 << "break";
1596 }
1597 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1598 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1599 << "continue";
1600 }
1601}
1602
John McCalldadc5752010-08-24 06:29:42 +00001603StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001604Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001605 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001606 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001607 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001608 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001609 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001610 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1611 // declare identifiers for objects having storage class 'auto' or
1612 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001613 for (auto *DI : DS->decls()) {
1614 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001615 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001616 VD = nullptr;
1617 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001618 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1619 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001620 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001621 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001622 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001623 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001624
Serge Pavlov09f99242014-01-23 15:05:00 +00001625 CheckBreakContinueBinding(second.get());
1626 CheckBreakContinueBinding(third.get());
1627
Richard Trieu451a5db2012-04-30 18:01:30 +00001628 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001629 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001630
John McCalldadc5752010-08-24 06:29:42 +00001631 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001632 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001633 if (secondVar) {
1634 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001635 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Meador Ingef0af05c2015-06-25 22:06:40 +00001636 SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001637 if (SecondResult.isInvalid())
1638 return StmtError();
1639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001641 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001642
Anders Carlsson1682af52009-08-01 01:39:59 +00001643 DiagnoseUnusedExprResult(First);
1644 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001645 DiagnoseUnusedExprResult(Body);
1646
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001647 if (isa<NullStmt>(Body))
1648 getCurCompoundScope().setHasEmptyLoopBodies();
1649
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001650 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1651 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001652}
1653
John McCall34376a62010-12-04 03:47:34 +00001654/// In an Objective C collection iteration statement:
1655/// for (x in y)
1656/// x can be an arbitrary l-value expression. Bind it up as a
1657/// full-expression.
1658StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001659 // Reduce placeholder expressions here. Note that this rejects the
1660 // use of pseudo-object l-values in this position.
1661 ExprResult result = CheckPlaceholderExpr(E);
1662 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001663 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001664
Richard Smith945f8d32013-01-14 22:39:08 +00001665 ExprResult FullExpr = ActOnFinishFullExpr(E);
1666 if (FullExpr.isInvalid())
1667 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001668 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001669}
1670
John McCall53848232011-07-27 01:07:15 +00001671ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001672Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1673 if (!collection)
1674 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001675
Kaelyn Takata15867822014-11-21 18:48:04 +00001676 ExprResult result = CorrectDelayedTyposInExpr(collection);
1677 if (!result.isUsable())
1678 return ExprError();
1679 collection = result.get();
1680
John McCall53848232011-07-27 01:07:15 +00001681 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001682 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001683
1684 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001685 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001686 if (result.isInvalid())
1687 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001688 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001689
1690 // The operand needs to have object-pointer type.
1691 // TODO: should we do a contextual conversion?
1692 const ObjCObjectPointerType *pointerType =
1693 collection->getType()->getAs<ObjCObjectPointerType>();
1694 if (!pointerType)
1695 return Diag(forLoc, diag::err_collection_expr_type)
1696 << collection->getType() << collection->getSourceRange();
1697
1698 // Check that the operand provides
1699 // - countByEnumeratingWithState:objects:count:
1700 const ObjCObjectType *objectType = pointerType->getObjectType();
1701 ObjCInterfaceDecl *iface = objectType->getInterface();
1702
1703 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001704 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001705 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001706 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001707 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001708 ? diag::err_arc_collection_forward
1709 : 0,
1710 collection)) {
John McCall53848232011-07-27 01:07:15 +00001711 // Otherwise, if we have any useful type information, check that
1712 // the type declares the appropriate method.
1713 } else if (iface || !objectType->qual_empty()) {
1714 IdentifierInfo *selectorIdents[] = {
1715 &Context.Idents.get("countByEnumeratingWithState"),
1716 &Context.Idents.get("objects"),
1717 &Context.Idents.get("count")
1718 };
1719 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1720
Craig Topperc3ec1492014-05-26 06:22:03 +00001721 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001722
1723 // If there's an interface, look in both the public and private APIs.
1724 if (iface) {
1725 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001726 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001727 }
1728
1729 // Also check protocol qualifiers.
1730 if (!method)
1731 method = LookupMethodInQualifiedType(selector, pointerType,
1732 /*instance*/ true);
1733
1734 // If we didn't find it anywhere, give up.
1735 if (!method) {
1736 Diag(forLoc, diag::warn_collection_expr_type)
1737 << collection->getType() << selector << collection->getSourceRange();
1738 }
1739
1740 // TODO: check for an incompatible signature?
1741 }
1742
1743 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001744 return collection;
John McCall53848232011-07-27 01:07:15 +00001745}
1746
John McCalldadc5752010-08-24 06:29:42 +00001747StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001748Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001749 Stmt *First, Expr *collection,
1750 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001751
1752 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001753 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001754
Fariborz Jahanian93977672008-01-10 20:33:58 +00001755 if (First) {
1756 QualType FirstType;
1757 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001758 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001759 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1760 diag::err_toomany_element_decls));
1761
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001762 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1763 if (!D || D->isInvalidDecl())
1764 return StmtError();
1765
John McCall31168b02011-06-15 23:02:42 +00001766 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001767 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1768 // declare identifiers for objects having storage class 'auto' or
1769 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001770 if (!D->hasLocalStorage())
1771 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001772 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001773
1774 // If the type contained 'auto', deduce the 'auto' to 'id'.
1775 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001776 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1777 VK_RValue);
1778 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001779 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1780 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001781 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001782 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001783 D->setInvalidDecl();
1784 return StmtError();
1785 }
1786
Richard Smith061f1e22013-04-30 21:23:01 +00001787 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001788
1789 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001790 SourceLocation Loc =
1791 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001792 Diag(Loc, diag::warn_auto_var_is_id)
1793 << D->getDeclName();
1794 }
1795 }
1796
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001797 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001798 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001799 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001800 return StmtError(Diag(First->getLocStart(),
1801 diag::err_selector_element_not_lvalue)
1802 << First->getSourceRange());
1803
Mike Stump11289f42009-09-09 15:08:12 +00001804 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001805 if (FirstType.isConstQualified())
1806 Diag(ForLoc, diag::err_selector_element_const_type)
1807 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001808 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001809 if (!FirstType->isDependentType() &&
1810 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001811 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001812 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1813 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001814 }
Chad Rosier02a84392012-08-10 17:56:09 +00001815
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001816 if (CollectionExprResult.isInvalid())
1817 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001818
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001819 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001820 if (CollectionExprResult.isInvalid())
1821 return StmtError();
1822
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001823 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1824 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001825}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001826
Richard Smith02e85f32011-04-14 22:09:26 +00001827/// Finish building a variable declaration for a for-range statement.
1828/// \return true if an error occurs.
1829static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001830 SourceLocation Loc, int DiagID) {
Kaelyn Takatafb8cf402015-05-07 00:11:02 +00001831 if (Decl->getType()->isUndeducedType()) {
1832 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1833 if (!Res.isUsable()) {
1834 Decl->setInvalidDecl();
1835 return true;
1836 }
1837 Init = Res.get();
1838 }
1839
Richard Smith02e85f32011-04-14 22:09:26 +00001840 // Deduce the type for the iterator variable now rather than leaving it to
1841 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001842 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001843 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001844 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001845 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001846 SemaRef.Diag(Loc, DiagID) << Init->getType();
1847 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001848 Decl->setInvalidDecl();
1849 return true;
1850 }
Richard Smith061f1e22013-04-30 21:23:01 +00001851 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001852
John McCall31168b02011-06-15 23:02:42 +00001853 // In ARC, infer lifetime.
1854 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1855 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001856 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001857 SemaRef.inferObjCARCLifetime(Decl))
1858 Decl->setInvalidDecl();
1859
Richard Smith02e85f32011-04-14 22:09:26 +00001860 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1861 /*TypeMayContainAuto=*/false);
1862 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001863 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001864 return false;
1865}
1866
Sam Panzer0f384432012-08-21 00:52:01 +00001867namespace {
1868
Richard Smith02e85f32011-04-14 22:09:26 +00001869/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001870/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001871/// nor from the diagnostics produced when analysing the implicit expressions
1872/// required in a for-range statement.
1873void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001874 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001875 CallExpr *CE = dyn_cast<CallExpr>(E);
1876 if (!CE)
1877 return;
1878 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1879 if (!D)
1880 return;
1881 SourceLocation Loc = D->getLocation();
1882
1883 std::string Description;
1884 bool IsTemplate = false;
1885 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1886 Description = SemaRef.getTemplateArgumentBindingsText(
1887 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1888 IsTemplate = true;
1889 }
1890
1891 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1892 << BEF << IsTemplate << Description << E->getType();
1893}
1894
Sam Panzer0f384432012-08-21 00:52:01 +00001895/// Build a variable declaration for a for-range statement.
1896VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1897 QualType Type, const char *Name) {
1898 DeclContext *DC = SemaRef.CurContext;
1899 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1900 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1901 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001902 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001903 Decl->setImplicit();
1904 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001905}
1906
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001907}
Richard Smith02e85f32011-04-14 22:09:26 +00001908
Fariborz Jahanian00213472012-07-06 19:04:04 +00001909static bool ObjCEnumerationCollection(Expr *Collection) {
1910 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001911 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001912}
1913
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001914/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001915///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001916/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001917/// A range-based for statement is equivalent to
1918///
1919/// {
1920/// auto && __range = range-init;
1921/// for ( auto __begin = begin-expr,
1922/// __end = end-expr;
1923/// __begin != __end;
1924/// ++__begin ) {
1925/// for-range-declaration = *__begin;
1926/// statement
1927/// }
1928/// }
1929///
1930/// The body of the loop is not available yet, since it cannot be analysed until
1931/// we have determined the type of the for-range-declaration.
1932StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001933Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001934 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001935 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001936 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001937 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001938
Richard Smith3249fed2013-08-21 01:40:36 +00001939 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001940 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001941
1942 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1943 assert(DS && "first part of for range not a decl stmt");
1944
1945 if (!DS->isSingleDecl()) {
1946 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1947 return StmtError();
1948 }
Richard Smith02e85f32011-04-14 22:09:26 +00001949
Richard Smith3249fed2013-08-21 01:40:36 +00001950 Decl *LoopVar = DS->getSingleDecl();
1951 if (LoopVar->isInvalidDecl() || !Range ||
1952 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1953 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001954 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001955 }
Richard Smith02e85f32011-04-14 22:09:26 +00001956
1957 // Build auto && __range = range-init
1958 SourceLocation RangeLoc = Range->getLocStart();
1959 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1960 Context.getAutoRRefDeductType(),
1961 "__range");
1962 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001963 diag::err_for_range_deduction_failure)) {
1964 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001965 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001966 }
Richard Smith02e85f32011-04-14 22:09:26 +00001967
1968 // Claim the type doesn't contain auto: we've already done the checking.
1969 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001970 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001971 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001972 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001973 if (RangeDecl.isInvalid()) {
1974 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001975 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001976 }
Richard Smith02e85f32011-04-14 22:09:26 +00001977
1978 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001979 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1980 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001981}
1982
1983/// \brief Create the initialization, compare, and increment steps for
1984/// the range-based for loop expression.
1985/// This function does not handle array-based for loops,
1986/// which are created in Sema::BuildCXXForRangeStmt.
1987///
1988/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1989/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1990/// CandidateSet and BEF are set and some non-success value is returned on
1991/// failure.
1992static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1993 Expr *BeginRange, Expr *EndRange,
1994 QualType RangeType,
1995 VarDecl *BeginVar,
1996 VarDecl *EndVar,
1997 SourceLocation ColonLoc,
1998 OverloadCandidateSet *CandidateSet,
1999 ExprResult *BeginExpr,
2000 ExprResult *EndExpr,
2001 Sema::BeginEndFunction *BEF) {
2002 DeclarationNameInfo BeginNameInfo(
2003 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2004 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2005 ColonLoc);
2006
2007 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2008 Sema::LookupMemberName);
2009 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2010
2011 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2012 // - if _RangeT is a class type, the unqualified-ids begin and end are
2013 // looked up in the scope of class _RangeT as if by class member access
2014 // lookup (3.4.5), and if either (or both) finds at least one
2015 // declaration, begin-expr and end-expr are __range.begin() and
2016 // __range.end(), respectively;
2017 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2018 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2019
2020 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2021 SourceLocation RangeLoc = BeginVar->getLocation();
2022 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2023
2024 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2025 << RangeLoc << BeginRange->getType() << *BEF;
2026 return Sema::FRS_DiagnosticIssued;
2027 }
2028 } else {
2029 // - otherwise, begin-expr and end-expr are begin(__range) and
2030 // end(__range), respectively, where begin and end are looked up with
2031 // argument-dependent lookup (3.4.2). For the purposes of this name
2032 // lookup, namespace std is an associated namespace.
2033
2034 }
2035
2036 *BEF = Sema::BEF_begin;
2037 Sema::ForRangeStatus RangeStatus =
2038 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2039 Sema::BEF_begin, BeginNameInfo,
2040 BeginMemberLookup, CandidateSet,
2041 BeginRange, BeginExpr);
2042
2043 if (RangeStatus != Sema::FRS_Success)
2044 return RangeStatus;
2045 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2046 diag::err_for_range_iter_deduction_failure)) {
2047 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2048 return Sema::FRS_DiagnosticIssued;
2049 }
2050
2051 *BEF = Sema::BEF_end;
2052 RangeStatus =
2053 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2054 Sema::BEF_end, EndNameInfo,
2055 EndMemberLookup, CandidateSet,
2056 EndRange, EndExpr);
2057 if (RangeStatus != Sema::FRS_Success)
2058 return RangeStatus;
2059 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2060 diag::err_for_range_iter_deduction_failure)) {
2061 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2062 return Sema::FRS_DiagnosticIssued;
2063 }
2064 return Sema::FRS_Success;
2065}
2066
2067/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002068/// If the attempt fails, this function will return a valid, null StmtResult
2069/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002070static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2071 SourceLocation ForLoc,
2072 Stmt *LoopVarDecl,
2073 SourceLocation ColonLoc,
2074 Expr *Range,
2075 SourceLocation RangeLoc,
2076 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002077 // Determine whether we can rebuild the for-range statement with a
2078 // dereferenced range expression.
2079 ExprResult AdjustedRange;
2080 {
2081 Sema::SFINAETrap Trap(SemaRef);
2082
2083 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2084 if (AdjustedRange.isInvalid())
2085 return StmtResult();
2086
2087 StmtResult SR =
2088 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2089 AdjustedRange.get(), RParenLoc,
2090 Sema::BFRK_Check);
2091 if (SR.isInvalid())
2092 return StmtResult();
2093 }
2094
2095 // The attempt to dereference worked well enough that it could produce a valid
2096 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2097 // case there are any other (non-fatal) problems with it.
2098 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2099 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2100 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2101 AdjustedRange.get(), RParenLoc,
2102 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002103}
2104
Richard Smith3249fed2013-08-21 01:40:36 +00002105namespace {
2106/// RAII object to automatically invalidate a declaration if an error occurs.
2107struct InvalidateOnErrorScope {
2108 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2109 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2110 ~InvalidateOnErrorScope() {
2111 if (Enabled && Trap.hasErrorOccurred())
2112 D->setInvalidDecl();
2113 }
2114
2115 DiagnosticErrorTrap Trap;
2116 Decl *D;
2117 bool Enabled;
2118};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002119}
Richard Smith3249fed2013-08-21 01:40:36 +00002120
Richard Smitha05b3b52012-09-20 21:52:32 +00002121/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002122StmtResult
2123Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2124 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2125 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002126 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002127 Scope *S = getCurScope();
2128
2129 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2130 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2131 QualType RangeVarType = RangeVar->getType();
2132
2133 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2134 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2135
Richard Smith3249fed2013-08-21 01:40:36 +00002136 // If we hit any errors, mark the loop variable as invalid if its type
2137 // contains 'auto'.
2138 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2139 LoopVar->getType()->isUndeducedType());
2140
Richard Smith02e85f32011-04-14 22:09:26 +00002141 StmtResult BeginEndDecl = BeginEnd;
2142 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2143
Richard Smith27d807c2013-04-30 13:56:41 +00002144 if (RangeVarType->isDependentType()) {
2145 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002146 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002147
2148 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2149 // them in properly when we instantiate the loop.
2150 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2151 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2152 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002153 SourceLocation RangeLoc = RangeVar->getLocation();
2154
Ted Kremenekbed648e2011-10-10 22:36:28 +00002155 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2156
2157 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2158 VK_LValue, ColonLoc);
2159 if (BeginRangeRef.isInvalid())
2160 return StmtError();
2161
2162 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2163 VK_LValue, ColonLoc);
2164 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002165 return StmtError();
2166
2167 QualType AutoType = Context.getAutoDeductType();
2168 Expr *Range = RangeVar->getInit();
2169 if (!Range)
2170 return StmtError();
2171 QualType RangeType = Range->getType();
2172
2173 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002174 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002175 return StmtError();
2176
2177 // Build auto __begin = begin-expr, __end = end-expr.
2178 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2179 "__begin");
2180 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2181 "__end");
2182
2183 // Build begin-expr and end-expr and attach to __begin and __end variables.
2184 ExprResult BeginExpr, EndExpr;
2185 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2186 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2187 // __range + __bound, respectively, where __bound is the array bound. If
2188 // _RangeT is an array of unknown size or an array of incomplete type,
2189 // the program is ill-formed;
2190
2191 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002192 BeginExpr = BeginRangeRef;
2193 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002194 diag::err_for_range_iter_deduction_failure)) {
2195 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2196 return StmtError();
2197 }
2198
2199 // Find the array bound.
2200 ExprResult BoundExpr;
2201 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002202 BoundExpr = IntegerLiteral::Create(
2203 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002204 else if (const VariableArrayType *VAT =
2205 dyn_cast<VariableArrayType>(UnqAT))
2206 BoundExpr = VAT->getSizeExpr();
2207 else {
2208 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2209 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002210 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002211 }
2212
2213 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002214 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002215 BoundExpr.get());
2216 if (EndExpr.isInvalid())
2217 return StmtError();
2218 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2219 diag::err_for_range_iter_deduction_failure)) {
2220 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2221 return StmtError();
2222 }
2223 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002224 OverloadCandidateSet CandidateSet(RangeLoc,
2225 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002226 Sema::BeginEndFunction BEFFailure;
2227 ForRangeStatus RangeStatus =
2228 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2229 EndRangeRef.get(), RangeType,
2230 BeginVar, EndVar, ColonLoc, &CandidateSet,
2231 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002232
Richard Smitha05b3b52012-09-20 21:52:32 +00002233 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002234 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002235 // If the range is being built from an array parameter, emit a
2236 // a diagnostic that it is being treated as a pointer.
2237 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2238 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2239 QualType ArrayTy = PVD->getOriginalType();
2240 QualType PointerTy = PVD->getType();
2241 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2242 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2243 << RangeLoc << PVD << ArrayTy << PointerTy;
2244 Diag(PVD->getLocation(), diag::note_declared_at);
2245 return StmtError();
2246 }
2247 }
2248 }
2249
2250 // If building the range failed, try dereferencing the range expression
2251 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002252 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2253 LoopVarDecl, ColonLoc,
2254 Range, RangeLoc,
2255 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002256 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002257 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002258 }
2259
Sam Panzer0f384432012-08-21 00:52:01 +00002260 // Otherwise, emit diagnostics if we haven't already.
2261 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002262 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002263 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2264 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002266 }
2267 // Return an error if no fix was discovered.
2268 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002269 return StmtError();
2270 }
2271
Sam Panzer0f384432012-08-21 00:52:01 +00002272 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2273 "invalid range expression in for loop");
2274
2275 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002276 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2277 if (!Context.hasSameType(BeginType, EndType)) {
2278 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2279 << BeginType << EndType;
2280 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2281 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2282 }
2283
2284 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2285 // Claim the type doesn't contain auto: we've already done the checking.
2286 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002287 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002288 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002289 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2290
Ted Kremenekbed648e2011-10-10 22:36:28 +00002291 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2292 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002293 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002294 if (BeginRef.isInvalid())
2295 return StmtError();
2296
Richard Smith02e85f32011-04-14 22:09:26 +00002297 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2298 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002299 if (EndRef.isInvalid())
2300 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002301
2302 // Build and check __begin != __end expression.
2303 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2304 BeginRef.get(), EndRef.get());
2305 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2306 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2307 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002308 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2309 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002310 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2311 if (!Context.hasSameType(BeginType, EndType))
2312 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2313 return StmtError();
2314 }
2315
2316 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002317 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2318 VK_LValue, ColonLoc);
2319 if (BeginRef.isInvalid())
2320 return StmtError();
2321
Richard Smith02e85f32011-04-14 22:09:26 +00002322 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2323 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2324 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002325 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2326 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002327 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2328 return StmtError();
2329 }
2330
2331 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002332 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2333 VK_LValue, ColonLoc);
2334 if (BeginRef.isInvalid())
2335 return StmtError();
2336
Richard Smith02e85f32011-04-14 22:09:26 +00002337 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2338 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002339 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2340 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002341 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2342 return StmtError();
2343 }
2344
Richard Smitha05b3b52012-09-20 21:52:32 +00002345 // Attach *__begin as initializer for VD. Don't touch it if we're just
2346 // trying to determine whether this would be a valid range.
2347 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002348 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2349 /*TypeMayContainAuto=*/true);
2350 if (LoopVar->isInvalidDecl())
2351 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2352 }
2353 }
2354
Richard Smitha05b3b52012-09-20 21:52:32 +00002355 // Don't bother to actually allocate the result if we're just trying to
2356 // determine whether it would be valid.
2357 if (Kind == BFRK_Check)
2358 return StmtResult();
2359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002360 return new (Context) CXXForRangeStmt(
2361 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2362 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002363}
2364
Chad Rosier02a84392012-08-10 17:56:09 +00002365/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002366/// statement.
2367StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2368 if (!S || !B)
2369 return StmtError();
2370 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002371
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002372 ForStmt->setBody(B);
2373 return S;
2374}
2375
Richard Trieu3e1d4832015-04-13 22:08:55 +00002376// Warn when the loop variable is a const reference that creates a copy.
2377// Suggest using the non-reference type for copies. If a copy can be prevented
2378// suggest the const reference type that would do so.
2379// For instance, given "for (const &Foo : Range)", suggest
2380// "for (const Foo : Range)" to denote a copy is made for the loop. If
2381// possible, also suggest "for (const &Bar : Range)" if this type prevents
2382// the copy altogether.
2383static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2384 const VarDecl *VD,
2385 QualType RangeInitType) {
2386 const Expr *InitExpr = VD->getInit();
2387 if (!InitExpr)
2388 return;
2389
2390 QualType VariableType = VD->getType();
2391
2392 const MaterializeTemporaryExpr *MTE =
2393 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2394
2395 // No copy made.
2396 if (!MTE)
2397 return;
2398
2399 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2400
2401 // Searching for either UnaryOperator for dereference of a pointer or
2402 // CXXOperatorCallExpr for handling iterators.
2403 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2404 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2405 E = CCE->getArg(0);
2406 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2407 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2408 E = ME->getBase();
2409 } else {
2410 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2411 E = MTE->GetTemporaryExpr();
2412 }
2413 E = E->IgnoreImpCasts();
2414 }
2415
2416 bool ReturnsReference = false;
2417 if (isa<UnaryOperator>(E)) {
2418 ReturnsReference = true;
2419 } else {
2420 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2421 const FunctionDecl *FD = Call->getDirectCallee();
2422 QualType ReturnType = FD->getReturnType();
2423 ReturnsReference = ReturnType->isReferenceType();
2424 }
2425
2426 if (ReturnsReference) {
2427 // Loop variable creates a temporary. Suggest either to go with
2428 // non-reference loop variable to indiciate a copy is made, or
2429 // the correct time to bind a const reference.
2430 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2431 << VD << VariableType << E->getType();
2432 QualType NonReferenceType = VariableType.getNonReferenceType();
2433 NonReferenceType.removeLocalConst();
2434 QualType NewReferenceType =
2435 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2436 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2437 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2438 } else {
2439 // The range always returns a copy, so a temporary is always created.
2440 // Suggest removing the reference from the loop variable.
2441 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2442 << VD << RangeInitType;
2443 QualType NonReferenceType = VariableType.getNonReferenceType();
2444 NonReferenceType.removeLocalConst();
2445 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2446 << NonReferenceType << VD->getSourceRange();
2447 }
2448}
2449
2450// Warns when the loop variable can be changed to a reference type to
2451// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2452// "for (const Foo &x : Range)" if this form does not make a copy.
2453static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2454 const VarDecl *VD) {
2455 const Expr *InitExpr = VD->getInit();
2456 if (!InitExpr)
2457 return;
2458
2459 QualType VariableType = VD->getType();
2460
2461 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2462 if (!CE->getConstructor()->isCopyConstructor())
2463 return;
2464 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2465 if (CE->getCastKind() != CK_LValueToRValue)
2466 return;
2467 } else {
2468 return;
2469 }
2470
2471 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2472 // should be emitted. Also, only ignore POD types with trivial copy
2473 // constructors.
2474 if (VariableType.isPODType(SemaRef.Context))
2475 return;
2476
2477 // Suggest changing from a const variable to a const reference variable
2478 // if doing so will prevent a copy.
2479 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2480 << VD << VariableType << InitExpr->getType();
2481 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2482 << SemaRef.Context.getLValueReferenceType(VariableType)
2483 << VD->getSourceRange();
2484}
2485
2486/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2487/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2488/// using "const foo x" to show that a copy is made
2489/// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2490/// Suggest either "const bar x" to keep the copying or "const foo& x" to
2491/// prevent the copy.
2492/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2493/// Suggest "const foo &x" to prevent the copy.
2494static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2495 const CXXForRangeStmt *ForStmt) {
2496 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2497 ForStmt->getLocStart()) &&
2498 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2499 ForStmt->getLocStart()) &&
2500 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2501 ForStmt->getLocStart())) {
2502 return;
2503 }
2504
2505 const VarDecl *VD = ForStmt->getLoopVariable();
2506 if (!VD)
2507 return;
2508
2509 QualType VariableType = VD->getType();
2510
2511 if (VariableType->isIncompleteType())
2512 return;
2513
2514 const Expr *InitExpr = VD->getInit();
2515 if (!InitExpr)
2516 return;
2517
2518 if (VariableType->isReferenceType()) {
2519 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2520 ForStmt->getRangeInit()->getType());
2521 } else if (VariableType.isConstQualified()) {
2522 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2523 }
2524}
2525
Richard Smith02e85f32011-04-14 22:09:26 +00002526/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2527/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2528/// body cannot be performed until after the type of the range variable is
2529/// determined.
2530StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2531 if (!S || !B)
2532 return StmtError();
2533
Fariborz Jahanian00213472012-07-06 19:04:04 +00002534 if (isa<ObjCForCollectionStmt>(S))
2535 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002536
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002537 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2538 ForStmt->setBody(B);
2539
2540 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2541 diag::warn_empty_range_based_for_body);
2542
Richard Trieu3e1d4832015-04-13 22:08:55 +00002543 DiagnoseForRangeVariableCopies(*this, ForStmt);
2544
Richard Smith02e85f32011-04-14 22:09:26 +00002545 return S;
2546}
2547
Chris Lattnercab02a62011-02-17 20:34:02 +00002548StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2549 SourceLocation LabelLoc,
2550 LabelDecl *TheDecl) {
2551 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002552 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002553 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002554}
Chris Lattner1c310502007-05-31 06:00:00 +00002555
John McCalldadc5752010-08-24 06:29:42 +00002556StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002557Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002558 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002559 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002560 if (!E->isTypeDependent()) {
2561 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002562 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002563 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002564 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002565 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2566 if (ExprRes.isInvalid())
2567 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002568 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002569 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002570 return StmtError();
2571 }
John McCalla95172b2010-08-01 00:26:45 +00002572
Richard Smith945f8d32013-01-14 22:39:08 +00002573 ExprResult ExprRes = ActOnFinishFullExpr(E);
2574 if (ExprRes.isInvalid())
2575 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002576 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002577
John McCallaab3e412010-08-25 08:40:02 +00002578 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002579
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002580 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002581}
2582
Nico Weberd64657f2015-03-09 02:47:59 +00002583static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2584 const Scope &DestScope) {
2585 if (!S.CurrentSEHFinally.empty() &&
2586 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2587 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2588 }
2589}
2590
John McCalldadc5752010-08-24 06:29:42 +00002591StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002592Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002593 Scope *S = CurScope->getContinueParent();
2594 if (!S) {
2595 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002596 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002597 }
Nico Weberd64657f2015-03-09 02:47:59 +00002598 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002599
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002600 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002601}
2602
John McCalldadc5752010-08-24 06:29:42 +00002603StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002604Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002605 Scope *S = CurScope->getBreakParent();
2606 if (!S) {
2607 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002608 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002609 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002610 if (S->isOpenMPLoopScope())
2611 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2612 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002613 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002614
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002615 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002616}
2617
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002619/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002620///
Douglas Gregor5d369002011-01-21 18:05:27 +00002621/// \param ReturnType If we're determining the copy elision candidate for
2622/// a return statement, this is the return type of the function. If we're
2623/// determining the copy elision candidate for a throw expression, this will
2624/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002625///
Douglas Gregor5d369002011-01-21 18:05:27 +00002626/// \param E The expression being returned from the function or block, or
2627/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002628///
Douglas Gregor86394412011-05-20 15:00:53 +00002629/// \param AllowFunctionParameter Whether we allow function parameters to
2630/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2631/// we re-use this logic to determine whether we should try to move as part of
2632/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002633///
2634/// \returns The NRVO candidate variable, if the return statement may use the
2635/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002636VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2637 Expr *E,
2638 bool AllowFunctionParameter) {
2639 if (!getLangOpts().CPlusPlus)
2640 return nullptr;
2641
2642 // - in a return statement in a function [where] ...
2643 // ... the expression is the name of a non-volatile automatic object ...
2644 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002645 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002646 return nullptr;
2647 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2648 if (!VD)
2649 return nullptr;
2650
2651 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2652 return VD;
2653 return nullptr;
2654}
2655
2656bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2657 bool AllowFunctionParameter) {
2658 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002659 // - in a return statement in a function with ...
2660 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002661 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002662 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002663 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002664 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002665 if (!VDType->isDependentType() &&
2666 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2667 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669
John McCall03318c12011-11-11 03:57:31 +00002670 // ...object (other than a function or catch-clause parameter)...
2671 if (VD->getKind() != Decl::Var &&
2672 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002673 return false;
2674 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002675
John McCall03318c12011-11-11 03:57:31 +00002676 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002677 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002678
2679 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002680 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002681
2682 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002683 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002684
2685 // Variables with higher required alignment than their type's ABI
2686 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002687 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002688 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002689 return false;
John McCall03318c12011-11-11 03:57:31 +00002690
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002691 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002692}
2693
Douglas Gregor626fbed2011-01-21 21:08:57 +00002694/// \brief Perform the initialization of a potentially-movable value, which
2695/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002696///
2697/// This routine implements C++0x [class.copy]p33, which attempts to treat
2698/// returned lvalues as rvalues in certain cases (to prefer move construction),
2699/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002701Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2702 const VarDecl *NRVOCandidate,
2703 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002704 Expr *Value,
2705 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002706 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707 // When the criteria for elision of a copy operation are met or would
2708 // be met save for the fact that the source object is a function
2709 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002710 // overload resolution to select the constructor for the copy is first
2711 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002712 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002713 if (AllowNRVO &&
2714 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002716 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002717
Douglas Gregorf282a762011-01-21 19:38:21 +00002718 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002719 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002720 = InitializationKind::CreateCopy(Value->getLocStart(),
2721 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002722 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002723
2724 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002725 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002726 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002727 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002728 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002729 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2730 StepEnd = Seq.step_end();
2731 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002732 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002733 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002734
2735 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002736 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002737
Douglas Gregorf282a762011-01-21 19:38:21 +00002738 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002739 = Constructor->getParamDecl(0)->getType()
2740 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002741
Douglas Gregorf282a762011-01-21 19:38:21 +00002742 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002743 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002744 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2745 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002746 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002747
Douglas Gregorf282a762011-01-21 19:38:21 +00002748 // Promote "AsRvalue" to the heap, since we now need this
2749 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002750 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002751 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752
Douglas Gregorf282a762011-01-21 19:38:21 +00002753 // Complete type-checking the initialization of the return type
2754 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002755 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002756 }
2757 }
2758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759
Douglas Gregorf282a762011-01-21 19:38:21 +00002760 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002762 // (again) now with the return value expression as written.
2763 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002764 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002765
Douglas Gregorf282a762011-01-21 19:38:21 +00002766 return Res;
2767}
2768
Richard Smith4db51c22013-09-25 05:02:54 +00002769/// \brief Determine whether the declared return type of the specified function
2770/// contains 'auto'.
2771static bool hasDeducedReturnType(FunctionDecl *FD) {
2772 const FunctionProtoType *FPT =
2773 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002774 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002775}
2776
Eli Friedman34b49062012-01-26 03:00:14 +00002777/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2778/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002779///
John McCalldadc5752010-08-24 06:29:42 +00002780StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002781Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2782 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002783 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002784 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002785 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002786 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002787
Richard Smith4db51c22013-09-25 05:02:54 +00002788 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2789 // In C++1y, the return type may involve 'auto'.
2790 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2791 FunctionDecl *FD = CurLambda->CallOperator;
2792 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002793 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002794
2795 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2796 assert(AT && "lost auto type from lambda return type");
2797 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2798 FD->setInvalidDecl();
2799 return StmtError();
2800 }
Alp Toker314cc812014-01-25 16:55:45 +00002801 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002802 } else if (CurCap->HasImplicitReturnType) {
2803 // For blocks/lambdas with implicit return types, we check each return
2804 // statement individually, and deduce the common return type when the block
2805 // or lambda is completed.
2806 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002807 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002808 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2809 if (Result.isInvalid())
2810 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002811 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002812
Richard Smith5a0e50c2014-12-19 22:10:51 +00002813 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2814 // when deducing a return type for a lambda-expression (or by extension
2815 // for a block). These rules differ from the stated C++11 rules only in
2816 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002817 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002818 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002819 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002820 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002821 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002822 if (RetValExp) {
2823 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2824 // initializer list, because it is not an expression (even
2825 // though we represent it as one). We still deduce 'void'.
2826 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2827 << RetValExp->getSourceRange();
2828 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002829
Jordan Rosed39e5f12012-07-02 21:19:23 +00002830 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002831 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002832
2833 // Although we'll properly infer the type of the block once it's completed,
2834 // make sure we provide a return type now for better error recovery.
2835 if (CurCap->ReturnType.isNull())
2836 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002837 }
Eli Friedman34b49062012-01-26 03:00:14 +00002838 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002839
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002840 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002841 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2842 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2843 return StmtError();
2844 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002845 } else if (CapturedRegionScopeInfo *CurRegion =
2846 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2847 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2848 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002849 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002850 assert(CurLambda && "unknown kind of captured scope");
2851 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2852 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002853 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2854 return StmtError();
2855 }
2856 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002857
Steve Naroffc540d662008-09-03 18:15:37 +00002858 // Otherwise, verify that this result type matches the previous one. We are
2859 // pickier with blocks than for normal functions because we don't have GCC
2860 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002861 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002862 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002863 // Delay processing for now. TODO: there are lots of dependent
2864 // types we can conclusively prove aren't void.
2865 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002866 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002867 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002868 (RetValExp->isTypeDependent() ||
2869 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002870 if (!getLangOpts().CPlusPlus &&
2871 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002872 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002873 else {
2874 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002876 }
Steve Naroffc540d662008-09-03 18:15:37 +00002877 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002878 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002879 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2880 } else if (!RetValExp->isTypeDependent()) {
2881 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002882
John McCall5500ef22011-08-17 22:09:46 +00002883 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2884 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2885 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002886
John McCall5500ef22011-08-17 22:09:46 +00002887 // In C++ the return statement is handled via a copy initialization.
2888 // the C version of which boils down to CheckSingleAssignmentConstraints.
2889 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2890 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2891 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002893 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2894 FnRetType, RetValExp);
2895 if (Res.isInvalid()) {
2896 // FIXME: Cleanup temporaries here, anyway?
2897 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002898 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002899 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002900 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002901 } else {
2902 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002903 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002904
John McCall75f92b52011-08-17 21:34:14 +00002905 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002906 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2907 if (ER.isInvalid())
2908 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002909 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002910 }
John McCall5500ef22011-08-17 22:09:46 +00002911 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2912 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002913
Jordan Rosed39e5f12012-07-02 21:19:23 +00002914 // If we need to check for the named return value optimization,
2915 // or if we need to infer the return type,
2916 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002917 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002918 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002920 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002921}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002922
Nico Weber72889432014-09-06 01:25:55 +00002923namespace {
2924/// \brief Marks all typedefs in all local classes in a type referenced.
2925///
2926/// In a function like
2927/// auto f() {
2928/// struct S { typedef int a; };
2929/// return S();
2930/// }
2931///
2932/// the local type escapes and could be referenced in some TUs but not in
2933/// others. Pretend that all local typedefs are always referenced, to not warn
2934/// on this. This isn't necessary if f has internal linkage, or the typedef
2935/// is private.
2936class LocalTypedefNameReferencer
2937 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2938public:
2939 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2940 bool VisitRecordType(const RecordType *RT);
2941private:
2942 Sema &S;
2943};
2944bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2945 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2946 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2947 R->isDependentType())
2948 return true;
2949 for (auto *TmpD : R->decls())
2950 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2951 if (T->getAccess() != AS_private || R->hasFriends())
2952 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2953 return true;
2954}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002955}
Nico Weber72889432014-09-06 01:25:55 +00002956
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002957TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002958 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002959 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2960 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002961 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002962}
2963
Richard Smith2a7d4812013-05-04 07:00:32 +00002964/// Deduce the return type for a function from a returned expression, per
2965/// C++1y [dcl.spec.auto]p6.
2966bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2967 SourceLocation ReturnLoc,
2968 Expr *&RetExpr,
2969 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002970 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002972
Richard Smithc58f38f2013-08-14 20:16:31 +00002973 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2974 // If the deduction is for a return statement and the initializer is
2975 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002976 Diag(RetExpr->getExprLoc(),
2977 getCurLambda() ? diag::err_lambda_return_init_list
2978 : diag::err_auto_fn_return_init_list)
2979 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002980 return true;
2981 }
2982
2983 if (FD->isDependentContext()) {
2984 // C++1y [dcl.spec.auto]p12:
2985 // Return type deduction [...] occurs when the definition is
2986 // instantiated even if the function body contains a return
2987 // statement with a non-type-dependent operand.
2988 assert(AT->isDeduced() && "should have deduced to dependent type");
2989 return false;
Douglas Gregor6032d5b2015-10-01 19:52:44 +00002990 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002991
Douglas Gregor6032d5b2015-10-01 19:52:44 +00002992 if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002993 // Otherwise, [...] deduce a value for U using the rules of template
2994 // argument deduction.
2995 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2996
2997 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2998 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2999 << OrigResultType.getType() << RetExpr->getType();
3000
3001 if (DAR != DAR_Succeeded)
3002 return true;
Nico Weber72889432014-09-06 01:25:55 +00003003
3004 // If a local type is part of the returned type, mark its fields as
3005 // referenced.
3006 LocalTypedefNameReferencer Referencer(*this);
3007 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00003008 } else {
3009 // In the case of a return with no operand, the initializer is considered
3010 // to be void().
3011 //
3012 // Deduction here can only succeed if the return type is exactly 'cv auto'
3013 // or 'decltype(auto)', so just check for that case directly.
3014 if (!OrigResultType.getType()->getAs<AutoType>()) {
3015 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3016 << OrigResultType.getType();
3017 return true;
3018 }
3019 // We always deduce U = void in this case.
3020 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3021 if (Deduced.isNull())
3022 return true;
3023 }
3024
3025 // If a function with a declared return type that contains a placeholder type
3026 // has multiple return statements, the return type is deduced for each return
3027 // statement. [...] if the type deduced is not the same in each deduction,
3028 // the program is ill-formed.
3029 if (AT->isDeduced() && !FD->isInvalidDecl()) {
3030 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00003031 if (!FD->isDependentContext() &&
3032 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00003033 const LambdaScopeInfo *LambdaSI = getCurLambda();
3034 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3035 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3036 << NewAT->getDeducedType() << AT->getDeducedType()
3037 << true /*IsLambda*/;
3038 } else {
3039 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3040 << (AT->isDecltypeAuto() ? 1 : 0)
3041 << NewAT->getDeducedType() << AT->getDeducedType();
3042 }
Richard Smith2a7d4812013-05-04 07:00:32 +00003043 return true;
3044 }
3045 } else if (!FD->isInvalidDecl()) {
3046 // Update all declarations of the function to have the deduced return type.
3047 Context.adjustDeducedFunctionResultType(FD, Deduced);
3048 }
3049
3050 return false;
3051}
3052
John McCalldadc5752010-08-24 06:29:42 +00003053StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003054Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3055 Scope *CurScope) {
3056 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3057 if (R.isInvalid()) {
3058 return R;
3059 }
3060
3061 if (VarDecl *VD =
3062 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3063 CurScope->addNRVOCandidate(VD);
3064 } else {
3065 CurScope->setNoNRVO();
3066 }
3067
Nico Weberd64657f2015-03-09 02:47:59 +00003068 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3069
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003070 return R;
3071}
3072
3073StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00003074 // Check for unexpanded parameter packs.
3075 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3076 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003077
Eli Friedman34b49062012-01-26 03:00:14 +00003078 if (isa<CapturingScopeInfo>(getCurFunction()))
3079 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003080
Chris Lattner79413952008-12-04 23:50:19 +00003081 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00003082 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003083 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003084 bool isObjCMethod = false;
3085
Mike Stumpd00bc1a2009-04-29 00:43:21 +00003086 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003087 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003088 if (FD->hasAttrs())
3089 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00003090 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00003091 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00003092 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00003093 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003094 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003095 isObjCMethod = true;
3096 if (MD->hasAttrs())
3097 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00003098 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3099 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00003100 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00003101 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00003102 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3103 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00003104 }
3105 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00003106 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00003107
Richard Smith2a7d4812013-05-04 07:00:32 +00003108 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3109 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003110 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003111 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3112 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00003113 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003114 FD->setInvalidDecl();
3115 return StmtError();
3116 } else {
Alp Toker314cc812014-01-25 16:55:45 +00003117 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003118 }
3119 }
3120 }
3121
Richard Smithc58f38f2013-08-14 20:16:31 +00003122 bool HasDependentReturnType = FnRetType->isDependentType();
3123
Craig Topperc3ec1492014-05-26 06:22:03 +00003124 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00003125 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003126 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003127 if (isa<InitListExpr>(RetValExp)) {
3128 // We simply never allow init lists as the return value of void
3129 // functions. This is compatible because this was never allowed before,
3130 // so there's no legacy code to deal with.
3131 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3132 int FunctionKind = 0;
3133 if (isa<ObjCMethodDecl>(CurDecl))
3134 FunctionKind = 1;
3135 else if (isa<CXXConstructorDecl>(CurDecl))
3136 FunctionKind = 2;
3137 else if (isa<CXXDestructorDecl>(CurDecl))
3138 FunctionKind = 3;
3139
3140 Diag(ReturnLoc, diag::err_return_init_list)
3141 << CurDecl->getDeclName() << FunctionKind
3142 << RetValExp->getSourceRange();
3143
3144 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00003145 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00003146 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003147 // C99 6.8.6.4p1 (ext_ since GCC warns)
3148 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003149 if (RetValExp->getType()->isVoidType()) {
3150 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3151 if (isa<CXXConstructorDecl>(CurDecl) ||
3152 isa<CXXDestructorDecl>(CurDecl))
3153 D = diag::err_ctor_dtor_returns_void;
3154 else
3155 D = diag::ext_return_has_void_expr;
3156 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003157 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003158 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003159 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003160 if (Result.isInvalid())
3161 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003162 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003163 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003164 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003165 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003166 // return of void in constructor/destructor is illegal in C++.
3167 if (D == diag::err_ctor_dtor_returns_void) {
3168 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3169 Diag(ReturnLoc, D)
3170 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3171 << RetValExp->getSourceRange();
3172 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003173 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003174 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003175 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003176 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003177
3178 int FunctionKind = 0;
3179 if (isa<ObjCMethodDecl>(CurDecl))
3180 FunctionKind = 1;
3181 else if (isa<CXXConstructorDecl>(CurDecl))
3182 FunctionKind = 2;
3183 else if (isa<CXXDestructorDecl>(CurDecl))
3184 FunctionKind = 3;
3185
Nick Lewycky1be750a2011-06-01 07:44:31 +00003186 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003187 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003188 << RetValExp->getSourceRange();
3189 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Sebastian Redleef474c2012-02-22 10:50:08 +00003192 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003193 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3194 if (ER.isInvalid())
3195 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003196 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003197 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003199
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003201 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003202 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003203
David Majnemer2887ad32014-12-13 08:12:56 +00003204 unsigned DiagID;
3205 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3206 // C++11 [stmt.return]p2
3207 DiagID = diag::err_constexpr_return_missing_expr;
3208 FD->setInvalidDecl();
3209 } else if (getLangOpts().C99) {
3210 // C99 6.8.6.4p1 (ext_ since GCC warns)
3211 DiagID = diag::ext_return_missing_expr;
3212 } else {
3213 // C90 6.6.6.4p4
3214 DiagID = diag::warn_return_missing_expr;
3215 }
3216
3217 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003218 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003219 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003220 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003221
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003222 Result = new (Context) ReturnStmt(ReturnLoc);
3223 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003224 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003225 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003226
3227 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3228
3229 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3230 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3231 // function return.
3232
3233 // In C++ the return statement is handled via a copy initialization,
3234 // the C version of which boils down to CheckSingleAssignmentConstraints.
3235 if (RetValExp)
3236 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003237 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003238 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003239 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003240 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003241 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003243 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003244 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003245 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003246 return StmtError();
3247 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003248 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003249
3250 // If we have a related result type, we need to implicitly
3251 // convert back to the formal result type. We can't pretend to
3252 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003253 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003254 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003255 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3256 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003257 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3258 if (Res.isInvalid()) {
3259 // FIXME: Clean up temporaries here anyway?
3260 return StmtError();
3261 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003262 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003263 }
3264
Artyom Skrobov9f213442014-01-24 11:10:39 +00003265 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3266 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268
John McCallacf0ee52010-10-08 02:01:28 +00003269 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003270 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3271 if (ER.isInvalid())
3272 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003273 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003274 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003275 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277
3278 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003279 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003280 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003281 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003282
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003283 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003284}
3285
John McCalldadc5752010-08-24 06:29:42 +00003286StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003287Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003288 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003289 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003290 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003291 if (Var && Var->isInvalidDecl())
3292 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003293
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003294 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003295}
3296
John McCalldadc5752010-08-24 06:29:42 +00003297StmtResult
John McCallb268a282010-08-23 23:25:46 +00003298Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003299 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003300}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003301
John McCalldadc5752010-08-24 06:29:42 +00003302StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003304 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003305 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003306 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3307
John McCallaab3e412010-08-25 08:40:02 +00003308 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003309 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003310 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3311 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003312}
3313
John McCall0bd3e402012-05-08 21:41:25 +00003314StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003315 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003316 ExprResult Result = DefaultLvalueConversion(Throw);
3317 if (Result.isInvalid())
3318 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003319
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003320 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003321 if (Result.isInvalid())
3322 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003323 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003324
Douglas Gregor2900c162010-04-22 21:44:01 +00003325 QualType ThrowType = Throw->getType();
3326 // Make sure the expression type is an ObjC pointer or "void *".
3327 if (!ThrowType->isDependentType() &&
3328 !ThrowType->isObjCObjectPointerType()) {
3329 const PointerType *PT = ThrowType->getAs<PointerType>();
3330 if (!PT || !PT->getPointeeType()->isVoidType())
3331 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3332 << Throw->getType() << Throw->getSourceRange());
3333 }
3334 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003335
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003336 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003337}
3338
John McCalldadc5752010-08-24 06:29:42 +00003339StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003341 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003342 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003343 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3344
John McCallb268a282010-08-23 23:25:46 +00003345 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003346 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003347 // in the context of an @catch clause).
3348 Scope *AtCatchParent = CurScope;
3349 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3350 AtCatchParent = AtCatchParent->getParent();
3351 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003352 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 }
John McCallb268a282010-08-23 23:25:46 +00003354 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003355}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003356
John McCalld9bb7432011-07-27 21:50:02 +00003357ExprResult
3358Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3359 ExprResult result = DefaultLvalueConversion(operand);
3360 if (result.isInvalid())
3361 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003362 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003363
3364 // Make sure the expression type is an ObjC pointer or "void *".
3365 QualType type = operand->getType();
3366 if (!type->isDependentType() &&
3367 !type->isObjCObjectPointerType()) {
3368 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003369 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3370 if (getLangOpts().CPlusPlus) {
3371 if (RequireCompleteType(atLoc, type,
3372 diag::err_incomplete_receiver_type))
3373 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3374 << type << operand->getSourceRange();
3375
3376 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3377 if (!result.isUsable())
3378 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3379 << type << operand->getSourceRange();
3380
3381 operand = result.get();
3382 } else {
3383 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3384 << type << operand->getSourceRange();
3385 }
3386 }
John McCalld9bb7432011-07-27 21:50:02 +00003387 }
3388
3389 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003390 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003391}
3392
John McCalldadc5752010-08-24 06:29:42 +00003393StmtResult
John McCallb268a282010-08-23 23:25:46 +00003394Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3395 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003396 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003397 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003398 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003399}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003400
3401/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3402/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003403StmtResult
John McCall48871652010-08-21 09:40:31 +00003404Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003405 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003406 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003407 return new (Context)
3408 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003409}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003410
John McCall31168b02011-06-15 23:02:42 +00003411StmtResult
3412Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3413 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003414 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003415}
3416
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003417namespace {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003418class CatchHandlerType {
3419 QualType QT;
3420 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003421
Aaron Ballman8aee642902015-04-08 00:05:29 +00003422 // This is a special constructor to be used only with DenseMapInfo's
3423 // getEmptyKey() and getTombstoneKey() functions.
3424 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3425 enum Unique { ForDenseMap };
3426 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3427
Sebastian Redl63c4da02009-07-29 17:15:45 +00003428public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003429 /// Used when creating a CatchHandlerType from a handler type; will determine
Eric Christopher2c4555a2015-06-19 01:52:53 +00003430 /// whether the type is a pointer or reference and will strip off the top
Aaron Ballman8aee642902015-04-08 00:05:29 +00003431 /// level pointer and cv-qualifiers.
3432 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3433 if (QT->isPointerType())
3434 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003435
Aaron Ballman8aee642902015-04-08 00:05:29 +00003436 if (IsPointer || QT->isReferenceType())
3437 QT = QT->getPointeeType();
3438 QT = QT.getUnqualifiedType();
3439 }
3440
3441 /// Used when creating a CatchHandlerType from a base class type; pretends the
3442 /// type passed in had the pointer qualifier, does not need to get an
3443 /// unqualified type.
3444 CatchHandlerType(QualType QT, bool IsPointer)
3445 : QT(QT), IsPointer(IsPointer) {}
3446
3447 QualType underlying() const { return QT; }
3448 bool isPointer() const { return IsPointer; }
3449
3450 friend bool operator==(const CatchHandlerType &LHS,
3451 const CatchHandlerType &RHS) {
3452 // If the pointer qualification does not match, we can return early.
3453 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003454 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003455 // Otherwise, check the underlying type without cv-qualifiers.
3456 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003457 }
3458};
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00003459} // namespace
Sebastian Redl63c4da02009-07-29 17:15:45 +00003460
Aaron Ballman8aee642902015-04-08 00:05:29 +00003461namespace llvm {
3462template <> struct DenseMapInfo<CatchHandlerType> {
3463 static CatchHandlerType getEmptyKey() {
3464 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3465 CatchHandlerType::ForDenseMap);
3466 }
3467
3468 static CatchHandlerType getTombstoneKey() {
3469 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3470 CatchHandlerType::ForDenseMap);
3471 }
3472
3473 static unsigned getHashValue(const CatchHandlerType &Base) {
3474 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3475 }
3476
3477 static bool isEqual(const CatchHandlerType &LHS,
3478 const CatchHandlerType &RHS) {
3479 return LHS == RHS;
3480 }
3481};
3482
3483// It's OK to treat CatchHandlerType as a POD type.
3484template <> struct isPodLike<CatchHandlerType> {
3485 static const bool value = true;
3486};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003487}
Aaron Ballman8aee642902015-04-08 00:05:29 +00003488
3489namespace {
3490class CatchTypePublicBases {
3491 ASTContext &Ctx;
3492 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3493 const bool CheckAgainstPointer;
3494
3495 CXXCatchStmt *FoundHandler;
3496 CanQualType FoundHandlerType;
3497
3498public:
3499 CatchTypePublicBases(
3500 ASTContext &Ctx,
3501 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3502 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3503 FoundHandler(nullptr) {}
3504
3505 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3506 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3507
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003508 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003509 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003510 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3511 auto M = TypesToCheck;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003512 auto I = M.find(Check);
3513 if (I != M.end()) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003514 FoundHandler = I->second;
3515 FoundHandlerType = Ctx.getCanonicalType(S->getType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003516 return true;
3517 }
3518 }
3519 return false;
3520 }
3521};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003522}
Dan Gohman28ade552010-07-26 21:25:24 +00003523
Sebastian Redl9b244a82008-12-22 21:35:02 +00003524/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3525/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003526StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3527 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003528 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003529 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003530 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003531 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003532
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003533 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3534 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3535
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003536 sema::FunctionScopeInfo *FSI = getCurFunction();
3537
Reid Klecknere7175912015-02-02 22:15:31 +00003538 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003539 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003540 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003541 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003542 }
3543
Robert Wilhelmcafda822013-08-22 09:20:03 +00003544 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003545 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003546 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003547
Aaron Ballman8aee642902015-04-08 00:05:29 +00003548 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003549 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003550 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003551
Aaron Ballman8aee642902015-04-08 00:05:29 +00003552 // Diagnose when the handler is a catch-all handler, but it isn't the last
3553 // handler for the try block. [except.handle]p5. Also, skip exception
3554 // declarations that are invalid, since we can't usefully report on them.
3555 if (!H->getExceptionDecl()) {
3556 if (i < NumHandlers - 1)
3557 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003558 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003559 } else if (H->getExceptionDecl()->isInvalidDecl())
3560 continue;
3561
3562 // Walk the type hierarchy to diagnose when this type has already been
3563 // handled (duplication), or cannot be handled (derivation inversion). We
3564 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003565 CatchHandlerType HandlerCHT =
3566 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003567
3568 // We can ignore whether the type is a reference or a pointer; we need the
3569 // underlying declaration type in order to get at the underlying record
3570 // decl, if there is one.
3571 QualType Underlying = HandlerCHT.underlying();
3572 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3573 if (!RD->hasDefinition())
3574 continue;
3575 // Check that none of the public, unambiguous base classes are in the
3576 // map ([except.handle]p1). Give the base classes the same pointer
3577 // qualification as the original type we are basing off of. This allows
3578 // comparison against the handler type using the same top-level pointer
3579 // as the original type.
3580 CXXBasePaths Paths;
3581 Paths.setOrigin(RD);
3582 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00003583 if (RD->lookupInBases(CTPB, Paths)) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003584 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3585 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3586 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3587 diag::warn_exception_caught_by_earlier_handler)
3588 << H->getCaughtType();
3589 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3590 diag::note_previous_exception_handler)
3591 << Problem->getCaughtType();
3592 }
3593 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003594 }
Mike Stump11289f42009-09-09 15:08:12 +00003595
Aaron Ballman8aee642902015-04-08 00:05:29 +00003596 // Add the type the list of ones we have handled; diagnose if we've already
3597 // handled it.
3598 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3599 if (!R.second) {
3600 const CXXCatchStmt *Problem = R.first->second;
3601 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3602 diag::warn_exception_caught_by_earlier_handler)
3603 << H->getCaughtType();
3604 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3605 diag::note_previous_exception_handler)
3606 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003607 }
3608 }
Mike Stump11289f42009-09-09 15:08:12 +00003609
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003610 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003611
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003612 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003613}
John Wiegley1c0675e2011-04-28 01:08:34 +00003614
Reid Klecknere7175912015-02-02 22:15:31 +00003615StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3616 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003617 assert(TryBlock && Handler);
3618
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003619 sema::FunctionScopeInfo *FSI = getCurFunction();
3620
Reid Klecknere7175912015-02-02 22:15:31 +00003621 // SEH __try is incompatible with C++ try. Borland appears to support this,
3622 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003623 if (!getLangOpts().Borland) {
3624 if (FSI->FirstCXXTryLoc.isValid()) {
3625 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3626 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3627 }
Reid Klecknere7175912015-02-02 22:15:31 +00003628 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003629
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003630 FSI->setHasSEHTry(TryLoc);
3631
3632 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3633 // track if they use SEH.
3634 DeclContext *DC = CurContext;
3635 while (DC && !DC->isFunctionOrMethod())
3636 DC = DC->getParent();
3637 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3638 if (FD)
3639 FD->setUsesSEHTry(true);
3640 else
3641 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003642
Reid Kleckner8819a402015-07-10 00:16:25 +00003643 // Reject __try on unsupported targets.
3644 if (!Context.getTargetInfo().isSEHTrySupported())
3645 Diag(TryLoc, diag::err_seh_try_unsupported);
3646
Reid Klecknere7175912015-02-02 22:15:31 +00003647 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003648}
3649
3650StmtResult
3651Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3652 Expr *FilterExpr,
3653 Stmt *Block) {
3654 assert(FilterExpr && Block);
3655
3656 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003657 return StmtError(Diag(FilterExpr->getExprLoc(),
3658 diag::err_filter_expression_integral)
3659 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003660 }
3661
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003662 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003663}
3664
Nico Weberd64657f2015-03-09 02:47:59 +00003665void Sema::ActOnStartSEHFinallyBlock() {
3666 CurrentSEHFinally.push_back(CurScope);
3667}
3668
Nico Weberce903292015-03-09 03:17:15 +00003669void Sema::ActOnAbortSEHFinallyBlock() {
3670 CurrentSEHFinally.pop_back();
3671}
3672
Nico Weberd64657f2015-03-09 02:47:59 +00003673StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003674 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003675 CurrentSEHFinally.pop_back();
3676 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003677}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003678
Nico Weberc7d05962014-07-06 22:32:59 +00003679StmtResult
3680Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003681 Scope *SEHTryParent = CurScope;
3682 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3683 SEHTryParent = SEHTryParent->getParent();
3684 if (!SEHTryParent)
3685 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003686 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003687
Nico Weber9b982072014-07-07 00:12:30 +00003688 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003689}
3690
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003691StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3692 bool IsIfExists,
3693 NestedNameSpecifierLoc QualifierLoc,
3694 DeclarationNameInfo NameInfo,
3695 Stmt *Nested)
3696{
3697 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003698 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003699 cast<CompoundStmt>(Nested));
3700}
3701
3702
Chad Rosier02a84392012-08-10 17:56:09 +00003703StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003704 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003705 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003706 UnqualifiedId &Name,
3707 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003708 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003709 SS.getWithLocInContext(Context),
3710 GetNameFromUnqualifiedId(Name),
3711 Nested);
3712}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003713
3714RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003715Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3716 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003717 DeclContext *DC = CurContext;
3718 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3719 DC = DC->getParent();
3720
Craig Topperc3ec1492014-05-26 06:22:03 +00003721 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003722 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003723 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3724 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003725 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003726 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003727
Alexey Bataev330de032014-10-29 12:21:55 +00003728 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003729 DC->addDecl(RD);
3730 RD->setImplicit();
3731 RD->startDefinition();
3732
Alexey Bataev9959db52014-05-06 10:08:46 +00003733 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003734 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003735 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003736 return RD;
3737}
3738
3739static void buildCapturedStmtCaptureList(
3740 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3741 SmallVectorImpl<Expr *> &CaptureInits,
3742 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3743
3744 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3745 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3746
3747 if (Cap->isThisCapture()) {
3748 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3749 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003750 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003751 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003752 } else if (Cap->isVLATypeCapture()) {
3753 Captures.push_back(
3754 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3755 CaptureInits.push_back(nullptr);
3756 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003757 }
3758
3759 assert(Cap->isReferenceCapture() &&
3760 "non-reference capture not yet implemented");
3761
3762 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3763 CapturedStmt::VCK_ByRef,
3764 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003765 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003766 }
3767}
3768
3769void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003770 CapturedRegionKind Kind,
3771 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003772 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003773 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003774
Alexey Bataev9959db52014-05-06 10:08:46 +00003775 // Build the context parameter
3776 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3777 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3778 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3779 ImplicitParamDecl *Param
3780 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3781 DC->addDecl(Param);
3782
3783 CD->setContextParam(0, Param);
3784
3785 // Enter the capturing scope for this captured region.
3786 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3787
3788 if (CurScope)
3789 PushDeclContext(CurScope, CD);
3790 else
3791 CurContext = CD;
3792
3793 PushExpressionEvaluationContext(PotentiallyEvaluated);
3794}
3795
3796void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3797 CapturedRegionKind Kind,
3798 ArrayRef<CapturedParamNameType> Params) {
3799 CapturedDecl *CD = nullptr;
3800 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3801
3802 // Build the context parameter
3803 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3804 bool ContextIsFound = false;
3805 unsigned ParamNum = 0;
3806 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3807 E = Params.end();
3808 I != E; ++I, ++ParamNum) {
3809 if (I->second.isNull()) {
3810 assert(!ContextIsFound &&
3811 "null type has been found already for '__context' parameter");
3812 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3813 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3814 ImplicitParamDecl *Param
3815 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3816 DC->addDecl(Param);
3817 CD->setContextParam(ParamNum, Param);
3818 ContextIsFound = true;
3819 } else {
3820 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3821 ImplicitParamDecl *Param
3822 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3823 DC->addDecl(Param);
3824 CD->setParam(ParamNum, Param);
3825 }
3826 }
3827 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003828 if (!ContextIsFound) {
3829 // Add __context implicitly if it is not specified.
3830 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3831 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3832 ImplicitParamDecl *Param =
3833 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3834 DC->addDecl(Param);
3835 CD->setContextParam(ParamNum, Param);
3836 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003837 // Enter the capturing scope for this captured region.
3838 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3839
3840 if (CurScope)
3841 PushDeclContext(CurScope, CD);
3842 else
3843 CurContext = CD;
3844
3845 PushExpressionEvaluationContext(PotentiallyEvaluated);
3846}
3847
Wei Pan17fbf6e2013-05-04 03:59:06 +00003848void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003849 DiscardCleanupsInEvaluationContext();
3850 PopExpressionEvaluationContext();
3851
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003852 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3853 RecordDecl *Record = RSI->TheRecordDecl;
3854 Record->setInvalidDecl();
3855
Aaron Ballman62e47c42014-03-10 13:43:55 +00003856 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003857 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3858 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003859
Wei Pan17fbf6e2013-05-04 03:59:06 +00003860 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003861 PopFunctionScopeInfo();
3862}
3863
3864StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3865 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3866
3867 SmallVector<CapturedStmt::Capture, 4> Captures;
3868 SmallVector<Expr *, 4> CaptureInits;
3869 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3870
3871 CapturedDecl *CD = RSI->TheCapturedDecl;
3872 RecordDecl *RD = RSI->TheRecordDecl;
3873
Wei Pan17fbf6e2013-05-04 03:59:06 +00003874 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3875 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003876 CaptureInits, CD, RD);
3877
3878 CD->setBody(Res->getCapturedStmt());
3879 RD->completeDefinition();
3880
Wei Pan17fbf6e2013-05-04 03:59:06 +00003881 DiscardCleanupsInEvaluationContext();
3882 PopExpressionEvaluationContext();
3883
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003884 PopDeclContext();
3885 PopFunctionScopeInfo();
3886
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003887 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003888}