blob: 5774f53c060fa72cf2a6d4a783e9d3457a7049c4 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/Preprocessor.h"
29#include "clang/Sema/Initialization.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000033#include "llvm/ADT/ArrayRef.h"
Aaron Ballman8aee642902015-04-08 00:05:29 +000034#include "llvm/ADT/DenseMap.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000036#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000037#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000038#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000041
Richard Smith945f8d32013-01-14 22:39:08 +000042StmtResult Sema::ActOnExprStmt(ExprResult FE) {
43 if (FE.isInvalid())
44 return StmtError();
45
46 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
47 /*DiscardedValue*/ true);
48 if (FE.isInvalid())
Douglas Gregora6e053e2010-12-15 01:34:56 +000049 return StmtError();
50
Chris Lattner903eb512008-07-25 23:18:17 +000051 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
52 // void expression for its side effects. Conversion to void allows any
53 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000054
Chris Lattner903eb512008-07-25 23:18:17 +000055 // Same thing in for stmt first clause (when expr) and third clause.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000056 return StmtResult(FE.getAs<Stmt>());
Chris Lattner1ec5f562007-06-27 05:38:08 +000057}
58
59
John McCalleaef89b2013-03-22 02:10:40 +000060StmtResult Sema::ActOnExprStmtError() {
61 DiscardCleanupsInEvaluationContext();
62 return StmtError();
63}
64
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000065StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000066 bool HasLeadingEmptyMacro) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000067 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
Chris Lattner0f203a72007-05-28 01:45:28 +000068}
69
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000070StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
71 SourceLocation EndLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000072 DeclGroupRef DG = dg.get();
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattnercbafe8d2009-04-12 20:13:14 +000074 // If we have an invalid decl, just return an error.
75 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000076
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000077 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
Steve Naroff2a8ad182007-05-29 22:59:26 +000078}
Chris Lattneraf8d5812006-11-10 05:07:45 +000079
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000080void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +000081 DeclGroupRef DG = dg.get();
Wei Panc4c76d12013-05-03 21:07:45 +000082
Douglas Gregor2eb1c572013-04-08 20:52:24 +000083 // If we don't have a declaration, or we have an invalid declaration,
84 // just return.
85 if (DG.isNull() || !DG.isSingleDecl())
86 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000087
Douglas Gregor2eb1c572013-04-08 20:52:24 +000088 Decl *decl = DG.getSingleDecl();
89 if (!decl || decl->isInvalidDecl())
90 return;
91
92 // Only variable declarations are permitted.
93 VarDecl *var = dyn_cast<VarDecl>(decl);
94 if (!var) {
95 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
96 decl->setInvalidDecl();
97 return;
98 }
John McCall31168b02011-06-15 23:02:42 +000099
John McCalld4631322011-06-17 06:42:21 +0000100 // foreach variables are never actually initialized in the way that
101 // the parser came up with.
Craig Topperc3ec1492014-05-26 06:22:03 +0000102 var->setInit(nullptr);
John McCall31168b02011-06-15 23:02:42 +0000103
John McCalld4631322011-06-17 06:42:21 +0000104 // In ARC, we don't need to retain the iteration variable of a fast
105 // enumeration loop. Rather than actually trying to catch that
106 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000107 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000108 QualType type = var->getType();
109
110 // Only do this if we inferred the lifetime. Inferred lifetime
111 // will show up as a local qualifier because explicit lifetime
112 // should have shown up as an AttributedType instead.
113 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
114 // Add 'const' and mark the variable as pseudo-strong.
115 var->setType(type.withConst());
116 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000117 }
118 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000119}
120
Richard Trieu99e1c952014-03-11 03:11:08 +0000121/// \brief Diagnose unused comparisons, both builtin and overloaded operators.
122/// For '==' and '!=', suggest fixits for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000123///
124/// Adding a cast to void (or other expression wrappers) will prevent the
125/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000126static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000127 SourceLocation Loc;
Richard Trieu99e1c952014-03-11 03:11:08 +0000128 bool IsNotEqual, CanAssign, IsRelational;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129
130 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000131 if (!Op->isComparisonOp())
Chandler Carruthe2669392011-08-17 09:34:37 +0000132 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000133
Richard Trieu99e1c952014-03-11 03:11:08 +0000134 IsRelational = Op->isRelationalOp();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000136 IsNotEqual = Op->getOpcode() == BO_NE;
137 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000138 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Richard Trieu99e1c952014-03-11 03:11:08 +0000139 switch (Op->getOperator()) {
140 default:
Chandler Carruthe2669392011-08-17 09:34:37 +0000141 return false;
Richard Trieu99e1c952014-03-11 03:11:08 +0000142 case OO_EqualEqual:
143 case OO_ExclaimEqual:
144 IsRelational = false;
145 break;
146 case OO_Less:
147 case OO_Greater:
148 case OO_GreaterEqual:
149 case OO_LessEqual:
150 IsRelational = true;
151 break;
152 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000153
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000154 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000155 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
156 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000157 } else {
158 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000159 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000160 }
161
162 // Suppress warnings when the operator, suspicious as it may be, comes from
163 // a macro expansion.
Matt Beaumont-Gayb1e71a72013-01-12 00:54:16 +0000164 if (S.SourceMgr.isMacroBodyExpansion(Loc))
Chandler Carruthe2669392011-08-17 09:34:37 +0000165 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000166
Chandler Carruthe2669392011-08-17 09:34:37 +0000167 S.Diag(Loc, diag::warn_unused_comparison)
Richard Trieu99e1c952014-03-11 03:11:08 +0000168 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000169
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000170 // If the LHS is a plausible entity to assign to, provide a fixit hint to
171 // correct common typos.
Richard Trieu99e1c952014-03-11 03:11:08 +0000172 if (!IsRelational && CanAssign) {
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000173 if (IsNotEqual)
174 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
175 << FixItHint::CreateReplacement(Loc, "|=");
176 else
177 S.Diag(Loc, diag::note_equality_comparison_to_assign)
178 << FixItHint::CreateReplacement(Loc, "=");
179 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000180
181 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000182}
183
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000184void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000185 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
186 return DiagnoseUnusedExprResult(Label->getSubStmt());
187
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000188 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000189 if (!E)
190 return;
Aaron Ballman78ecb872014-10-16 20:13:28 +0000191
192 // If we are in an unevaluated expression context, then there can be no unused
193 // results because the results aren't expected to be used in the first place.
194 if (isUnevaluatedContext())
195 return;
196
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000197 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000198 // In most cases, we don't want to warn if the expression is written in a
199 // macro body, or if the macro comes from a system header. If the offending
200 // expression is a call to a function with the warn_unused_result attribute,
201 // we warn no matter the location. Because of the order in which the various
202 // checks need to happen, we factor out the macro-related test here.
203 bool ShouldSuppress =
204 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
205 SourceMgr.isInSystemMacro(ExprLoc);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000206
Eli Friedmanc11535c2012-05-24 00:47:05 +0000207 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000208 SourceLocation Loc;
209 SourceRange R1, R2;
Matt Beaumont-Gay978cca92013-01-17 02:06:08 +0000210 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000211 return;
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner6dc7e572012-08-31 22:39:21 +0000213 // If this is a GNU statement expression expanded from a macro, it is probably
214 // unused because it is a function-like macro that can be used as either an
215 // expression or statement. Don't warn, because it is almost certainly a
216 // false positive.
217 if (isa<StmtExpr>(E) && Loc.isMacroID())
218 return;
219
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000220 // Okay, we have an unused result. Depending on what the base expression is,
221 // we might want to make a more specific diagnostic. Check for one of these
222 // cases now.
223 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000224 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000225 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000226 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
227 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000228
Chandler Carruthe2669392011-08-17 09:34:37 +0000229 if (DiagnoseUnusedComparison(*this, E))
230 return;
231
Eli Friedmanc11535c2012-05-24 00:47:05 +0000232 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000233 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000234 if (E->getType()->isVoidType())
235 return;
236
Chris Lattner1a6babf2009-10-13 04:53:48 +0000237 // If the callee has attribute pure, const, or warn_unused_result, warn with
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000238 // a more specific message to make it clear what is happening. If the call
239 // is written in a macro body, only warn if it has the warn_unused_result
240 // attribute.
Nuno Lopes518e3702009-12-20 23:11:08 +0000241 if (const Decl *FD = CE->getCalleeDecl()) {
Aaron Ballman9ead1242013-12-19 02:39:40 +0000242 if (FD->hasAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000243 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000244 return;
245 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000246 if (ShouldSuppress)
247 return;
Aaron Ballman9ead1242013-12-19 02:39:40 +0000248 if (FD->hasAttr<PureAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000249 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
250 return;
251 }
Aaron Ballman9ead1242013-12-19 02:39:40 +0000252 if (FD->hasAttr<ConstAttr>()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000253 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
254 return;
255 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256 }
Matt Beaumont-Gay1c417da2013-02-26 19:34:08 +0000257 } else if (ShouldSuppress)
258 return;
259
260 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000261 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000262 Diag(Loc, diag::err_arc_unused_init_message) << R1;
263 return;
264 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000265 const ObjCMethodDecl *MD = ME->getMethodDecl();
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +0000266 if (MD) {
267 if (MD->hasAttr<WarnUnusedResultAttr>()) {
268 Diag(Loc, diag::warn_unused_result) << R1 << R2;
269 return;
270 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000271 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000272 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
273 const Expr *Source = POE->getSyntacticForm();
274 if (isa<ObjCSubscriptRefExpr>(Source))
275 DiagID = diag::warn_unused_container_subscript_expr;
276 else
277 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000278 } else if (const CXXFunctionalCastExpr *FC
279 = dyn_cast<CXXFunctionalCastExpr>(E)) {
280 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
281 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
282 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000283 }
John McCall2351cb92010-04-06 22:24:14 +0000284 // Diagnose "(void*) blah" as a typo for "(void) blah".
285 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
286 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
287 QualType T = TI->getType();
288
289 // We really do want to use the non-canonical type here.
290 if (T == Context.VoidPtrTy) {
David Blaikie6adc78e2013-02-18 22:06:02 +0000291 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
John McCall2351cb92010-04-06 22:24:14 +0000292
293 Diag(Loc, diag::warn_unused_voidptr)
294 << FixItHint::CreateRemoval(TL.getStarLoc());
295 return;
296 }
297 }
298
Eli Friedmanc11535c2012-05-24 00:47:05 +0000299 if (E->isGLValue() && E->getType().isVolatileQualified()) {
300 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
301 return;
302 }
303
Craig Topperc3ec1492014-05-26 06:22:03 +0000304 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000305}
306
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000307void Sema::ActOnStartOfCompoundStmt() {
308 PushCompoundScope();
309}
310
311void Sema::ActOnFinishOfCompoundStmt() {
312 PopCompoundScope();
313}
314
315sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
316 return getCurFunction()->CompoundScopes.back();
317}
318
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +0000319StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
320 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
321 const unsigned NumElts = Elts.size();
322
Chris Lattnerd864daf2007-08-27 04:29:41 +0000323 // If we're in C89 mode, check that we don't have any decls after stmts. If
324 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000325 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000326 // Note that __extension__ can be around a decl.
327 unsigned i = 0;
328 // Skip over all declarations.
329 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
330 /*empty*/;
331
332 // We found the end of the list or a statement. Scan for another declstmt.
333 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
334 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000335
Chris Lattnerd864daf2007-08-27 04:29:41 +0000336 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000337 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000338 Diag(D->getLocation(), diag::ext_mixed_decls_code);
339 }
340 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000341 // Warn about unused expressions in statements.
342 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000343 // Ignore statements that are last in a statement expression.
344 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000345 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000346
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000347 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000348 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000349
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000350 // Check for suspicious empty body (null statement) in `for' and `while'
351 // statements. Don't do anything for template instantiations, this just adds
352 // noise.
353 if (NumElts != 0 && !CurrentInstantiationScope &&
354 getCurCompoundScope().HasEmptyLoopBodies) {
355 for (unsigned i = 0; i != NumElts - 1; ++i)
356 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
357 }
358
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000359 return new (Context) CompoundStmt(Context, Elts, L, R);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000360}
361
John McCalldadc5752010-08-24 06:29:42 +0000362StmtResult
John McCallb268a282010-08-23 23:25:46 +0000363Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
364 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000365 SourceLocation ColonLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000366 assert(LHSVal && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000367
John McCallaab3e412010-08-25 08:40:02 +0000368 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000369 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000370 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000371 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000372
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000373 ExprResult LHS =
374 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
375 if (!getLangOpts().CPlusPlus11)
376 return VerifyIntegerConstantExpression(E);
377 if (Expr *CondExpr =
378 getCurFunction()->SwitchStack.back()->getCond()) {
379 QualType CondType = CondExpr->getType();
380 llvm::APSInt TempVal;
381 return CheckConvertedConstantExpression(E, CondType, TempVal,
382 CCEK_CaseValue);
383 }
384 return ExprError();
385 });
386 if (LHS.isInvalid())
387 return StmtError();
388 LHSVal = LHS.get();
389
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000390 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +0000391 // C99 6.8.4.2p3: The expression shall be an integer constant.
392 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000393 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000394 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000395 if (!LHSVal)
396 return StmtError();
397 }
Richard Smithf8379a02012-01-18 23:55:52 +0000398
399 // GCC extension: The expression shall be an integer constant.
400
Richard Smithf4c51d92012-02-04 09:53:13 +0000401 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000402 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
Richard Smithf4c51d92012-02-04 09:53:13 +0000403 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000404 }
405 }
Ben Langmuir2e13dd62013-04-29 13:07:42 +0000406
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000407 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
Richard Smith5b555da2014-11-20 01:24:12 +0000408 getLangOpts().CPlusPlus11);
409 if (LHS.isInvalid())
410 return StmtError();
Richard Smithf8379a02012-01-18 23:55:52 +0000411
Richard Smith5b555da2014-11-20 01:24:12 +0000412 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
413 getLangOpts().CPlusPlus11)
414 : ExprResult();
415 if (RHS.isInvalid())
416 return StmtError();
417
418 CaseStmt *CS = new (Context)
419 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000420 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000421 return CS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000422}
423
Chris Lattner34a22092009-03-04 04:23:07 +0000424/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000425void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000426 DiagnoseUnusedExprResult(SubStmt);
427
Chris Lattner34a22092009-03-04 04:23:07 +0000428 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000429 CS->setSubStmt(SubStmt);
430}
431
John McCalldadc5752010-08-24 06:29:42 +0000432StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000433Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000434 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000435 DiagnoseUnusedExprResult(SubStmt);
436
John McCallaab3e412010-08-25 08:40:02 +0000437 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000438 Diag(DefaultLoc, diag::err_default_not_in_switch);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000439 return SubStmt;
Chris Lattner39407372007-07-21 03:00:26 +0000440 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000441
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000442 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000443 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000444 return DS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000445}
446
John McCalldadc5752010-08-24 06:29:42 +0000447StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000448Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
449 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000450 // If the label was multiply defined, reject it now.
451 if (TheDecl->getStmt()) {
452 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
453 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000454 return SubStmt;
Chris Lattnere2473062007-05-28 06:28:18 +0000455 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000456
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000457 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000458 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
459 TheDecl->setStmt(LS);
Abramo Bagnara598b9432012-10-15 21:07:44 +0000460 if (!TheDecl->isGnuLocal()) {
461 TheDecl->setLocStart(IdentLoc);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000462 if (!TheDecl->isMSAsmLabel()) {
463 // Don't update the location of MS ASM labels. These will result in
464 // a diagnostic, and changing the location here will mess that up.
465 TheDecl->setLocation(IdentLoc);
466 }
Abramo Bagnara598b9432012-10-15 21:07:44 +0000467 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000468 return LS;
Chris Lattneraf8d5812006-11-10 05:07:45 +0000469}
470
Richard Smithc202b282012-04-14 00:33:13 +0000471StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000472 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000473 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000474 // Fill in the declaration and return it.
475 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000476 return LS;
Richard Smithc202b282012-04-14 00:33:13 +0000477}
478
John McCalldadc5752010-08-24 06:29:42 +0000479StmtResult
John McCall48871652010-08-21 09:40:31 +0000480Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000481 Stmt *thenStmt, SourceLocation ElseLoc,
482 Stmt *elseStmt) {
Argyrios Kyrtzidise6e422b2013-02-15 18:34:13 +0000483 // If the condition was invalid, discard the if statement. We could recover
484 // better by replacing it with a valid expr, but don't do that yet.
485 if (!CondVal.get() && !CondVar) {
486 getCurFunction()->setHasDroppedStmt();
487 return StmtError();
488 }
489
John McCalldadc5752010-08-24 06:29:42 +0000490 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000491
Craig Topperc3ec1492014-05-26 06:22:03 +0000492 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000493 if (CondVar) {
494 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000495 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000496 if (CondResult.isInvalid())
497 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000498 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000499 Expr *ConditionExpr = CondResult.getAs<Expr>();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000500 if (!ConditionExpr)
501 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000503 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000504
John McCallb268a282010-08-23 23:25:46 +0000505 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000506 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
507 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000508 }
509
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000510 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000511
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000512 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
513 thenStmt, ElseLoc, elseStmt);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000514}
Steve Naroff86272ea2007-05-29 02:14:17 +0000515
Chris Lattner67998452007-08-23 18:29:20 +0000516namespace {
517 struct CaseCompareFunctor {
518 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
519 const llvm::APSInt &RHS) {
520 return LHS.first < RHS;
521 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000522 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
523 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
524 return LHS.first < RHS.first;
525 }
Chris Lattner67998452007-08-23 18:29:20 +0000526 bool operator()(const llvm::APSInt &LHS,
527 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
528 return LHS < RHS.first;
529 }
530 };
531}
532
Chris Lattner4b2ff022007-09-21 18:15:22 +0000533/// CmpCaseVals - Comparison predicate for sorting case values.
534///
535static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
536 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
537 if (lhs.first < rhs.first)
538 return true;
539
540 if (lhs.first == rhs.first &&
541 lhs.second->getCaseLoc().getRawEncoding()
542 < rhs.second->getCaseLoc().getRawEncoding())
543 return true;
544 return false;
545}
546
Douglas Gregorbd6839732010-02-08 22:24:16 +0000547/// CmpEnumVals - Comparison predicate for sorting enumeration values.
548///
549static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
550 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
551{
552 return lhs.first < rhs.first;
553}
554
555/// EqEnumVals - Comparison preficate for uniqing enumeration values.
556///
557static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
558 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
559{
560 return lhs.first == rhs.first;
561}
562
Chris Lattnera96d4272009-10-16 16:45:22 +0000563/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
564/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000565static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
566 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
567 expr = cleanups->getSubExpr();
568 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
569 if (impcast->getCastKind() != CK_IntegralCast) break;
570 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000571 }
572 return expr->getType();
573}
574
John McCalldadc5752010-08-24 06:29:42 +0000575StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000577 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000578 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000579
Craig Topperc3ec1492014-05-26 06:22:03 +0000580 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +0000581 if (CondVar) {
582 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000583 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
584 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000585 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000586
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000587 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
John McCallb268a282010-08-23 23:25:46 +0000590 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000591 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregore2b37442012-05-04 22:38:52 +0000593 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
594 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000595
Douglas Gregore2b37442012-05-04 22:38:52 +0000596 public:
597 SwitchConvertDiagnoser(Expr *Cond)
Richard Smithccc11812013-05-21 19:05:48 +0000598 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
599 Cond(Cond) {}
Chad Rosiercc6a9082012-06-20 18:51:04 +0000600
Craig Toppere14c0f82014-03-12 04:55:44 +0000601 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
602 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000603 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
604 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000605
Craig Toppere14c0f82014-03-12 04:55:44 +0000606 SemaDiagnosticBuilder diagnoseIncomplete(
607 Sema &S, SourceLocation Loc, QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000608 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
609 << T << Cond->getSourceRange();
610 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000611
Craig Toppere14c0f82014-03-12 04:55:44 +0000612 SemaDiagnosticBuilder diagnoseExplicitConv(
613 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000614 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
615 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000616
Craig Toppere14c0f82014-03-12 04:55:44 +0000617 SemaDiagnosticBuilder noteExplicitConv(
618 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000619 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
620 << ConvTy->isEnumeralType() << ConvTy;
621 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000622
Craig Toppere14c0f82014-03-12 04:55:44 +0000623 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
624 QualType T) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000625 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
626 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000627
Craig Toppere14c0f82014-03-12 04:55:44 +0000628 SemaDiagnosticBuilder noteAmbiguous(
629 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Douglas Gregore2b37442012-05-04 22:38:52 +0000630 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
631 << ConvTy->isEnumeralType() << ConvTy;
632 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000633
Craig Toppere14c0f82014-03-12 04:55:44 +0000634 SemaDiagnosticBuilder diagnoseConversion(
635 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +0000636 llvm_unreachable("conversion functions are permitted");
Douglas Gregore2b37442012-05-04 22:38:52 +0000637 }
638 } SwitchDiagnoser(Cond);
639
Richard Smithccc11812013-05-21 19:05:48 +0000640 CondResult =
641 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
John McCallb268a282010-08-23 23:25:46 +0000642 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000643 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000644
John McCall5939b162011-08-06 07:30:58 +0000645 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
646 CondResult = UsualUnaryConversions(Cond);
647 if (CondResult.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000648 Cond = CondResult.get();
John McCall5939b162011-08-06 07:30:58 +0000649
John McCall48871652010-08-21 09:40:31 +0000650 if (!CondVar) {
Richard Smith945f8d32013-01-14 22:39:08 +0000651 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
John McCallb268a282010-08-23 23:25:46 +0000652 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000653 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000654 Cond = CondResult.get();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000655 }
John McCalla95172b2010-08-01 00:26:45 +0000656
John McCallaab3e412010-08-25 08:40:02 +0000657 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
John McCallb268a282010-08-23 23:25:46 +0000659 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000660 getCurFunction()->SwitchStack.push_back(SS);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000661 return SS;
Chris Lattner8fd2d012010-01-24 01:50:29 +0000662}
663
Gabor Greif16e02862010-10-01 22:05:14 +0000664static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
Richard Smith077d0832014-08-04 00:40:48 +0000665 Val = Val.extOrTrunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000666 Val.setIsSigned(IsSigned);
667}
668
Richard Smith077d0832014-08-04 00:40:48 +0000669/// Check the specified case value is in range for the given unpromoted switch
670/// type.
671static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
672 unsigned UnpromotedWidth, bool UnpromotedSign) {
673 // If the case value was signed and negative and the switch expression is
674 // unsigned, don't bother to warn: this is implementation-defined behavior.
675 // FIXME: Introduce a second, default-ignored warning for this case?
676 if (UnpromotedWidth < Val.getBitWidth()) {
677 llvm::APSInt ConvVal(Val);
678 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
679 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
680 // FIXME: Use different diagnostics for overflow in conversion to promoted
681 // type versus "switch expression cannot have this value". Use proper
682 // IntRange checking rather than just looking at the unpromoted type here.
683 if (ConvVal != Val)
684 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
685 << ConvVal.toString(10);
686 }
687}
688
Alexis Hunt724f14e2014-11-28 00:53:20 +0000689typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
690
Dmitri Gribenko58683752013-12-05 22:52:07 +0000691/// Returns true if we should emit a diagnostic about this case expression not
692/// being a part of the enum used in the switch controlling expression.
Alexis Hunt724f14e2014-11-28 00:53:20 +0000693static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
Dmitri Gribenko58683752013-12-05 22:52:07 +0000694 const EnumDecl *ED,
Alexis Hunt724f14e2014-11-28 00:53:20 +0000695 const Expr *CaseExpr,
696 EnumValsTy::iterator &EI,
697 EnumValsTy::iterator &EIEnd,
698 const llvm::APSInt &Val) {
699 bool FlagType = ED->hasAttr<FlagEnumAttr>();
700
701 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
712 if (FlagType) {
713 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);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001230 if (CondResult.isInvalid())
1231 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001232 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001233 Expr *ConditionExpr = CondResult.get();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001234 if (!ConditionExpr)
1235 return StmtError();
Serge Pavlov09f99242014-01-23 15:05:00 +00001236 CheckBreakContinueBinding(ConditionExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237
John McCallb268a282010-08-23 23:25:46 +00001238 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001239
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001240 if (isa<NullStmt>(Body))
1241 getCurCompoundScope().setHasEmptyLoopBodies();
1242
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001243 return new (Context)
1244 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001245}
1246
John McCalldadc5752010-08-24 06:29:42 +00001247StmtResult
John McCallb268a282010-08-23 23:25:46 +00001248Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001249 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001250 Expr *Cond, SourceLocation CondRParen) {
1251 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001252
Serge Pavlov09f99242014-01-23 15:05:00 +00001253 CheckBreakContinueBinding(Cond);
John Wiegley01296292011-04-08 18:41:53 +00001254 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
Dmitri Gribenkod4bc5ac2012-11-18 22:28:42 +00001255 if (CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001256 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001257 Cond = CondResult.get();
Steve Naroff86272ea2007-05-29 02:14:17 +00001258
Richard Smith945f8d32013-01-14 22:39:08 +00001259 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
John McCallb268a282010-08-23 23:25:46 +00001260 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001261 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001262 Cond = CondResult.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001263
John McCallb268a282010-08-23 23:25:46 +00001264 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001265
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001266 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001267}
1268
Richard Trieu451a5db2012-04-30 18:01:30 +00001269namespace {
1270 // This visitor will traverse a conditional statement and store all
1271 // the evaluated decls into a vector. Simple is set to true if none
1272 // of the excluded constructs are used.
1273 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001274 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Craig Topperfa159c12013-07-14 16:47:36 +00001275 SmallVectorImpl<SourceRange> &Ranges;
Richard Trieu451a5db2012-04-30 18:01:30 +00001276 bool Simple;
Richard Trieu9d228802013-05-31 22:46:45 +00001277 public:
1278 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001279
Craig Topper4dd9b432014-08-17 23:49:53 +00001280 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Craig Topperfa159c12013-07-14 16:47:36 +00001281 SmallVectorImpl<SourceRange> &Ranges) :
Richard Trieu9d228802013-05-31 22:46:45 +00001282 Inherited(S.Context),
1283 Decls(Decls),
1284 Ranges(Ranges),
1285 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001286
Richard Trieu9d228802013-05-31 22:46:45 +00001287 bool isSimple() { return Simple; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001288
Richard Trieu9d228802013-05-31 22:46:45 +00001289 // Replaces the method in EvaluatedExprVisitor.
1290 void VisitMemberExpr(MemberExpr* E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001291 Simple = false;
Richard Trieu9d228802013-05-31 22:46:45 +00001292 }
1293
1294 // Any Stmt not whitelisted will cause the condition to be marked complex.
1295 void VisitStmt(Stmt *S) {
1296 Simple = false;
1297 }
1298
1299 void VisitBinaryOperator(BinaryOperator *E) {
1300 Visit(E->getLHS());
1301 Visit(E->getRHS());
1302 }
1303
1304 void VisitCastExpr(CastExpr *E) {
Richard Trieu451a5db2012-04-30 18:01:30 +00001305 Visit(E->getSubExpr());
Richard Trieu9d228802013-05-31 22:46:45 +00001306 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001307
Richard Trieu9d228802013-05-31 22:46:45 +00001308 void VisitUnaryOperator(UnaryOperator *E) {
1309 // Skip checking conditionals with derefernces.
1310 if (E->getOpcode() == UO_Deref)
1311 Simple = false;
1312 else
1313 Visit(E->getSubExpr());
1314 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001315
Richard Trieu9d228802013-05-31 22:46:45 +00001316 void VisitConditionalOperator(ConditionalOperator *E) {
1317 Visit(E->getCond());
1318 Visit(E->getTrueExpr());
1319 Visit(E->getFalseExpr());
1320 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001321
Richard Trieu9d228802013-05-31 22:46:45 +00001322 void VisitParenExpr(ParenExpr *E) {
1323 Visit(E->getSubExpr());
1324 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001325
Richard Trieu9d228802013-05-31 22:46:45 +00001326 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1327 Visit(E->getOpaqueValue()->getSourceExpr());
1328 Visit(E->getFalseExpr());
1329 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001330
Richard Trieu9d228802013-05-31 22:46:45 +00001331 void VisitIntegerLiteral(IntegerLiteral *E) { }
1332 void VisitFloatingLiteral(FloatingLiteral *E) { }
1333 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1334 void VisitCharacterLiteral(CharacterLiteral *E) { }
1335 void VisitGNUNullExpr(GNUNullExpr *E) { }
1336 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
Richard Trieu451a5db2012-04-30 18:01:30 +00001337
Richard Trieu9d228802013-05-31 22:46:45 +00001338 void VisitDeclRefExpr(DeclRefExpr *E) {
1339 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1340 if (!VD) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001341
Richard Trieu9d228802013-05-31 22:46:45 +00001342 Ranges.push_back(E->getSourceRange());
1343
1344 Decls.insert(VD);
1345 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001346
1347 }; // end class DeclExtractor
1348
1349 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001350 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001351 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
Craig Topper4dd9b432014-08-17 23:49:53 +00001352 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
Richard Trieu451a5db2012-04-30 18:01:30 +00001353 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001354
Richard Trieu9d228802013-05-31 22:46:45 +00001355 public:
1356 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
Richard Trieu451a5db2012-04-30 18:01:30 +00001357
Craig Topper4dd9b432014-08-17 23:49:53 +00001358 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
Richard Trieu9d228802013-05-31 22:46:45 +00001359 Stmt *Statement) :
1360 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1361 if (!Statement) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001362
Richard Trieu9d228802013-05-31 22:46:45 +00001363 Visit(Statement);
Richard Trieu451a5db2012-04-30 18:01:30 +00001364 }
1365
Richard Trieu9d228802013-05-31 22:46:45 +00001366 void VisitReturnStmt(ReturnStmt *S) {
1367 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001368 }
1369
Richard Trieu9d228802013-05-31 22:46:45 +00001370 void VisitBreakStmt(BreakStmt *S) {
1371 FoundDecl = true;
Richard Trieu451a5db2012-04-30 18:01:30 +00001372 }
1373
Richard Trieu9d228802013-05-31 22:46:45 +00001374 void VisitGotoStmt(GotoStmt *S) {
1375 FoundDecl = true;
1376 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001377
Richard Trieu9d228802013-05-31 22:46:45 +00001378 void VisitCastExpr(CastExpr *E) {
1379 if (E->getCastKind() == CK_LValueToRValue)
1380 CheckLValueToRValueCast(E->getSubExpr());
1381 else
1382 Visit(E->getSubExpr());
1383 }
Richard Trieu451a5db2012-04-30 18:01:30 +00001384
Richard Trieu9d228802013-05-31 22:46:45 +00001385 void CheckLValueToRValueCast(Expr *E) {
1386 E = E->IgnoreParenImpCasts();
1387
1388 if (isa<DeclRefExpr>(E)) {
1389 return;
1390 }
1391
1392 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1393 Visit(CO->getCond());
1394 CheckLValueToRValueCast(CO->getTrueExpr());
1395 CheckLValueToRValueCast(CO->getFalseExpr());
1396 return;
1397 }
1398
1399 if (BinaryConditionalOperator *BCO =
1400 dyn_cast<BinaryConditionalOperator>(E)) {
1401 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1402 CheckLValueToRValueCast(BCO->getFalseExpr());
1403 return;
1404 }
1405
1406 Visit(E);
1407 }
1408
1409 void VisitDeclRefExpr(DeclRefExpr *E) {
1410 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1411 if (Decls.count(VD))
1412 FoundDecl = true;
1413 }
1414
1415 bool FoundDeclInUse() { return FoundDecl; }
Richard Trieu451a5db2012-04-30 18:01:30 +00001416
1417 }; // end class DeclMatcher
1418
1419 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1420 Expr *Third, Stmt *Body) {
1421 // Condition is empty
1422 if (!Second) return;
1423
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001424 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1425 Second->getLocStart()))
Richard Trieu451a5db2012-04-30 18:01:30 +00001426 return;
1427
1428 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1429 llvm::SmallPtrSet<VarDecl*, 8> Decls;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001430 SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001431 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001432 DE.Visit(Second);
1433
1434 // Don't analyze complex conditionals.
1435 if (!DE.isSimple()) return;
1436
1437 // No decls found.
1438 if (Decls.size() == 0) return;
1439
Richard Trieu0030f1d2012-05-04 03:01:54 +00001440 // Don't warn on volatile, static, or global variables.
Craig Topper4dd9b432014-08-17 23:49:53 +00001441 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1442 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001443 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001444 if ((*I)->getType().isVolatileQualified() ||
1445 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001446
1447 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1448 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1449 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1450 return;
1451
1452 // Load decl names into diagnostic.
1453 if (Decls.size() > 4)
1454 PDiag << 0;
1455 else {
1456 PDiag << Decls.size();
Craig Topper4dd9b432014-08-17 23:49:53 +00001457 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1458 E = Decls.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001459 I != E; ++I)
1460 PDiag << (*I)->getDeclName();
1461 }
1462
1463 // Load SourceRanges into diagnostic if there is room.
1464 // Otherwise, load the SourceRange of the conditional expression.
1465 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
Craig Topper2341c0d2013-07-04 03:08:24 +00001466 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001467 E = Ranges.end();
Richard Trieu451a5db2012-04-30 18:01:30 +00001468 I != E; ++I)
1469 PDiag << *I;
1470 else
1471 PDiag << Second->getSourceRange();
1472
1473 S.Diag(Ranges.begin()->getBegin(), PDiag);
1474 }
1475
Richard Trieu4e7c9622013-08-06 21:31:54 +00001476 // If Statement is an incemement or decrement, return true and sets the
1477 // variables Increment and DRE.
1478 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1479 DeclRefExpr *&DRE) {
1480 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1481 switch (UO->getOpcode()) {
1482 default: return false;
1483 case UO_PostInc:
1484 case UO_PreInc:
1485 Increment = true;
1486 break;
1487 case UO_PostDec:
1488 case UO_PreDec:
1489 Increment = false;
1490 break;
1491 }
1492 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1493 return DRE;
1494 }
1495
1496 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1497 FunctionDecl *FD = Call->getDirectCallee();
1498 if (!FD || !FD->isOverloadedOperator()) return false;
1499 switch (FD->getOverloadedOperator()) {
1500 default: return false;
1501 case OO_PlusPlus:
1502 Increment = true;
1503 break;
1504 case OO_MinusMinus:
1505 Increment = false;
1506 break;
1507 }
1508 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1509 return DRE;
1510 }
1511
1512 return false;
1513 }
1514
Serge Pavlov09f99242014-01-23 15:05:00 +00001515 // A visitor to determine if a continue or break statement is a
1516 // subexpression.
1517 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1518 SourceLocation BreakLoc;
1519 SourceLocation ContinueLoc;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001520 public:
Serge Pavlov09f99242014-01-23 15:05:00 +00001521 BreakContinueFinder(Sema &S, Stmt* Body) :
1522 Inherited(S.Context) {
Richard Trieu4e7c9622013-08-06 21:31:54 +00001523 Visit(Body);
1524 }
1525
Serge Pavlov09f99242014-01-23 15:05:00 +00001526 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001527
1528 void VisitContinueStmt(ContinueStmt* E) {
Serge Pavlov09f99242014-01-23 15:05:00 +00001529 ContinueLoc = E->getContinueLoc();
Richard Trieu4e7c9622013-08-06 21:31:54 +00001530 }
1531
Serge Pavlov09f99242014-01-23 15:05:00 +00001532 void VisitBreakStmt(BreakStmt* E) {
1533 BreakLoc = E->getBreakLoc();
1534 }
Richard Trieu4e7c9622013-08-06 21:31:54 +00001535
Serge Pavlov09f99242014-01-23 15:05:00 +00001536 bool ContinueFound() { return ContinueLoc.isValid(); }
1537 bool BreakFound() { return BreakLoc.isValid(); }
1538 SourceLocation GetContinueLoc() { return ContinueLoc; }
1539 SourceLocation GetBreakLoc() { return BreakLoc; }
1540
1541 }; // end class BreakContinueFinder
Richard Trieu4e7c9622013-08-06 21:31:54 +00001542
1543 // Emit a warning when a loop increment/decrement appears twice per loop
1544 // iteration. The conditions which trigger this warning are:
1545 // 1) The last statement in the loop body and the third expression in the
1546 // for loop are both increment or both decrement of the same variable
1547 // 2) No continue statements in the loop body.
1548 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1549 // Return when there is nothing to check.
1550 if (!Body || !Third) return;
1551
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001552 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1553 Third->getLocStart()))
Richard Trieu4e7c9622013-08-06 21:31:54 +00001554 return;
1555
1556 // Get the last statement from the loop body.
1557 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1558 if (!CS || CS->body_empty()) return;
1559 Stmt *LastStmt = CS->body_back();
1560 if (!LastStmt) return;
1561
1562 bool LoopIncrement, LastIncrement;
1563 DeclRefExpr *LoopDRE, *LastDRE;
1564
1565 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1566 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1567
1568 // Check that the two statements are both increments or both decrements
Serge Pavlov09f99242014-01-23 15:05:00 +00001569 // on the same variable.
Richard Trieu4e7c9622013-08-06 21:31:54 +00001570 if (LoopIncrement != LastIncrement ||
1571 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1572
Serge Pavlov09f99242014-01-23 15:05:00 +00001573 if (BreakContinueFinder(S, Body).ContinueFound()) return;
Richard Trieu4e7c9622013-08-06 21:31:54 +00001574
1575 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1576 << LastDRE->getDecl() << LastIncrement;
1577 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1578 << LoopIncrement;
1579 }
1580
Richard Trieu451a5db2012-04-30 18:01:30 +00001581} // end namespace
1582
Serge Pavlov09f99242014-01-23 15:05:00 +00001583
1584void Sema::CheckBreakContinueBinding(Expr *E) {
1585 if (!E || getLangOpts().CPlusPlus)
1586 return;
1587 BreakContinueFinder BCFinder(*this, E);
1588 Scope *BreakParent = CurScope->getBreakParent();
1589 if (BCFinder.BreakFound() && BreakParent) {
1590 if (BreakParent->getFlags() & Scope::SwitchScope) {
1591 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1592 } else {
1593 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1594 << "break";
1595 }
1596 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1597 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1598 << "continue";
1599 }
1600}
1601
John McCalldadc5752010-08-24 06:29:42 +00001602StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001603Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001604 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001605 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001606 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001607 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001608 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001609 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1610 // declare identifiers for objects having storage class 'auto' or
1611 // 'register'.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001612 for (auto *DI : DS->decls()) {
1613 VarDecl *VD = dyn_cast<VarDecl>(DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001614 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Craig Topperc3ec1492014-05-26 06:22:03 +00001615 VD = nullptr;
1616 if (!VD) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001617 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1618 DI->setInvalidDecl();
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001619 }
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001620 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001621 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001622 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001623
Serge Pavlov09f99242014-01-23 15:05:00 +00001624 CheckBreakContinueBinding(second.get());
1625 CheckBreakContinueBinding(third.get());
1626
Richard Trieu451a5db2012-04-30 18:01:30 +00001627 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
Richard Trieu4e7c9622013-08-06 21:31:54 +00001628 CheckForRedundantIteration(*this, third.get(), Body);
Richard Trieu451a5db2012-04-30 18:01:30 +00001629
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult SecondResult(second.release());
Craig Topperc3ec1492014-05-26 06:22:03 +00001631 VarDecl *ConditionVar = nullptr;
John McCall48871652010-08-21 09:40:31 +00001632 if (secondVar) {
1633 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001634 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001635 if (SecondResult.isInvalid())
1636 return StmtError();
1637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001639 Expr *Third = third.release().getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640
Anders Carlsson1682af52009-08-01 01:39:59 +00001641 DiagnoseUnusedExprResult(First);
1642 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001643 DiagnoseUnusedExprResult(Body);
1644
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001645 if (isa<NullStmt>(Body))
1646 getCurCompoundScope().setHasEmptyLoopBodies();
1647
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001648 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1649 Third, Body, ForLoc, LParenLoc, RParenLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001650}
1651
John McCall34376a62010-12-04 03:47:34 +00001652/// In an Objective C collection iteration statement:
1653/// for (x in y)
1654/// x can be an arbitrary l-value expression. Bind it up as a
1655/// full-expression.
1656StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001657 // Reduce placeholder expressions here. Note that this rejects the
1658 // use of pseudo-object l-values in this position.
1659 ExprResult result = CheckPlaceholderExpr(E);
1660 if (result.isInvalid()) return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001661 E = result.get();
John McCallbc153352012-03-30 05:43:39 +00001662
Richard Smith945f8d32013-01-14 22:39:08 +00001663 ExprResult FullExpr = ActOnFinishFullExpr(E);
1664 if (FullExpr.isInvalid())
1665 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001666 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
John McCall34376a62010-12-04 03:47:34 +00001667}
1668
John McCall53848232011-07-27 01:07:15 +00001669ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001670Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1671 if (!collection)
1672 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001673
Kaelyn Takata15867822014-11-21 18:48:04 +00001674 ExprResult result = CorrectDelayedTyposInExpr(collection);
1675 if (!result.isUsable())
1676 return ExprError();
1677 collection = result.get();
1678
John McCall53848232011-07-27 01:07:15 +00001679 // Bail out early if we've got a type-dependent expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001680 if (collection->isTypeDependent()) return collection;
John McCall53848232011-07-27 01:07:15 +00001681
1682 // Perform normal l-value conversion.
Kaelyn Takata15867822014-11-21 18:48:04 +00001683 result = DefaultFunctionArrayLvalueConversion(collection);
John McCall53848232011-07-27 01:07:15 +00001684 if (result.isInvalid())
1685 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001686 collection = result.get();
John McCall53848232011-07-27 01:07:15 +00001687
1688 // The operand needs to have object-pointer type.
1689 // TODO: should we do a contextual conversion?
1690 const ObjCObjectPointerType *pointerType =
1691 collection->getType()->getAs<ObjCObjectPointerType>();
1692 if (!pointerType)
1693 return Diag(forLoc, diag::err_collection_expr_type)
1694 << collection->getType() << collection->getSourceRange();
1695
1696 // Check that the operand provides
1697 // - countByEnumeratingWithState:objects:count:
1698 const ObjCObjectType *objectType = pointerType->getObjectType();
1699 ObjCInterfaceDecl *iface = objectType->getInterface();
1700
1701 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001702 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001703 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001704 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001705 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001706 ? diag::err_arc_collection_forward
1707 : 0,
1708 collection)) {
John McCall53848232011-07-27 01:07:15 +00001709 // Otherwise, if we have any useful type information, check that
1710 // the type declares the appropriate method.
1711 } else if (iface || !objectType->qual_empty()) {
1712 IdentifierInfo *selectorIdents[] = {
1713 &Context.Idents.get("countByEnumeratingWithState"),
1714 &Context.Idents.get("objects"),
1715 &Context.Idents.get("count")
1716 };
1717 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1718
Craig Topperc3ec1492014-05-26 06:22:03 +00001719 ObjCMethodDecl *method = nullptr;
John McCall53848232011-07-27 01:07:15 +00001720
1721 // If there's an interface, look in both the public and private APIs.
1722 if (iface) {
1723 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001724 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001725 }
1726
1727 // Also check protocol qualifiers.
1728 if (!method)
1729 method = LookupMethodInQualifiedType(selector, pointerType,
1730 /*instance*/ true);
1731
1732 // If we didn't find it anywhere, give up.
1733 if (!method) {
1734 Diag(forLoc, diag::warn_collection_expr_type)
1735 << collection->getType() << selector << collection->getSourceRange();
1736 }
1737
1738 // TODO: check for an incompatible signature?
1739 }
1740
1741 // Wrap up any cleanups in the expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001742 return collection;
John McCall53848232011-07-27 01:07:15 +00001743}
1744
John McCalldadc5752010-08-24 06:29:42 +00001745StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001746Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001747 Stmt *First, Expr *collection,
1748 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001749
1750 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001751 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001752
Fariborz Jahanian93977672008-01-10 20:33:58 +00001753 if (First) {
1754 QualType FirstType;
1755 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001756 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001757 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1758 diag::err_toomany_element_decls));
1759
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001760 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1761 if (!D || D->isInvalidDecl())
1762 return StmtError();
1763
John McCall31168b02011-06-15 23:02:42 +00001764 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001765 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1766 // declare identifiers for objects having storage class 'auto' or
1767 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001768 if (!D->hasLocalStorage())
1769 return StmtError(Diag(D->getLocation(),
Douglas Gregor2eb1c572013-04-08 20:52:24 +00001770 diag::err_non_local_variable_decl_in_for));
Douglas Gregorc430f452013-04-08 18:25:02 +00001771
1772 // If the type contained 'auto', deduce the 'auto' to 'id'.
1773 if (FirstType->getContainedAutoType()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001774 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1775 VK_RValue);
1776 Expr *DeducedInit = &OpaqueId;
Richard Smith061f1e22013-04-30 21:23:01 +00001777 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1778 DAR_Failed)
Douglas Gregorc430f452013-04-08 18:25:02 +00001779 DiagnoseAutoDeductionFailure(D, DeducedInit);
Richard Smith061f1e22013-04-30 21:23:01 +00001780 if (FirstType.isNull()) {
Douglas Gregorc430f452013-04-08 18:25:02 +00001781 D->setInvalidDecl();
1782 return StmtError();
1783 }
1784
Richard Smith061f1e22013-04-30 21:23:01 +00001785 D->setType(FirstType);
Douglas Gregorc430f452013-04-08 18:25:02 +00001786
1787 if (ActiveTemplateInstantiations.empty()) {
Richard Smith061f1e22013-04-30 21:23:01 +00001788 SourceLocation Loc =
1789 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Douglas Gregorc430f452013-04-08 18:25:02 +00001790 Diag(Loc, diag::warn_auto_var_is_id)
1791 << D->getDeclName();
1792 }
1793 }
1794
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001795 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001796 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001797 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001798 return StmtError(Diag(First->getLocStart(),
1799 diag::err_selector_element_not_lvalue)
1800 << First->getSourceRange());
1801
Mike Stump11289f42009-09-09 15:08:12 +00001802 FirstType = static_cast<Expr*>(First)->getType();
Fariborz Jahanian8bcf1822013-10-10 21:58:04 +00001803 if (FirstType.isConstQualified())
1804 Diag(ForLoc, diag::err_selector_element_const_type)
1805 << FirstType << First->getSourceRange();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001806 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001807 if (!FirstType->isDependentType() &&
1808 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001809 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001810 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1811 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001812 }
Chad Rosier02a84392012-08-10 17:56:09 +00001813
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001814 if (CollectionExprResult.isInvalid())
1815 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001816
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001817 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
Richard Smith945f8d32013-01-14 22:39:08 +00001818 if (CollectionExprResult.isInvalid())
1819 return StmtError();
1820
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001821 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1822 nullptr, ForLoc, RParenLoc);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001823}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001824
Richard Smith02e85f32011-04-14 22:09:26 +00001825/// Finish building a variable declaration for a for-range statement.
1826/// \return true if an error occurs.
1827static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
Richard Smith061f1e22013-04-30 21:23:01 +00001828 SourceLocation Loc, int DiagID) {
Richard Smith02e85f32011-04-14 22:09:26 +00001829 // Deduce the type for the iterator variable now rather than leaving it to
1830 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
Richard Smith061f1e22013-04-30 21:23:01 +00001831 QualType InitType;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001832 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Richard Smith061f1e22013-04-30 21:23:01 +00001833 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001834 Sema::DAR_Failed)
Richard Smith061f1e22013-04-30 21:23:01 +00001835 SemaRef.Diag(Loc, DiagID) << Init->getType();
1836 if (InitType.isNull()) {
Richard Smith02e85f32011-04-14 22:09:26 +00001837 Decl->setInvalidDecl();
1838 return true;
1839 }
Richard Smith061f1e22013-04-30 21:23:01 +00001840 Decl->setType(InitType);
Richard Smith02e85f32011-04-14 22:09:26 +00001841
John McCall31168b02011-06-15 23:02:42 +00001842 // In ARC, infer lifetime.
1843 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1844 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001845 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001846 SemaRef.inferObjCARCLifetime(Decl))
1847 Decl->setInvalidDecl();
1848
Richard Smith02e85f32011-04-14 22:09:26 +00001849 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1850 /*TypeMayContainAuto=*/false);
1851 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001852 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001853 return false;
1854}
1855
Sam Panzer0f384432012-08-21 00:52:01 +00001856namespace {
1857
Richard Smith02e85f32011-04-14 22:09:26 +00001858/// Produce a note indicating which begin/end function was implicitly called
Sam Panzer0f384432012-08-21 00:52:01 +00001859/// by a C++11 for-range statement. This is often not obvious from the code,
Richard Smith02e85f32011-04-14 22:09:26 +00001860/// nor from the diagnostics produced when analysing the implicit expressions
1861/// required in a for-range statement.
1862void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
Sam Panzer0f384432012-08-21 00:52:01 +00001863 Sema::BeginEndFunction BEF) {
Richard Smith02e85f32011-04-14 22:09:26 +00001864 CallExpr *CE = dyn_cast<CallExpr>(E);
1865 if (!CE)
1866 return;
1867 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1868 if (!D)
1869 return;
1870 SourceLocation Loc = D->getLocation();
1871
1872 std::string Description;
1873 bool IsTemplate = false;
1874 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1875 Description = SemaRef.getTemplateArgumentBindingsText(
1876 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1877 IsTemplate = true;
1878 }
1879
1880 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1881 << BEF << IsTemplate << Description << E->getType();
1882}
1883
Sam Panzer0f384432012-08-21 00:52:01 +00001884/// Build a variable declaration for a for-range statement.
1885VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1886 QualType Type, const char *Name) {
1887 DeclContext *DC = SemaRef.CurContext;
1888 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1889 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1890 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001891 TInfo, SC_None);
Sam Panzer0f384432012-08-21 00:52:01 +00001892 Decl->setImplicit();
1893 return Decl;
Richard Smith02e85f32011-04-14 22:09:26 +00001894}
1895
1896}
1897
Fariborz Jahanian00213472012-07-06 19:04:04 +00001898static bool ObjCEnumerationCollection(Expr *Collection) {
1899 return !Collection->isTypeDependent()
Craig Topperc3ec1492014-05-26 06:22:03 +00001900 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
Fariborz Jahanian00213472012-07-06 19:04:04 +00001901}
1902
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001903/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00001904///
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001905/// C++11 [stmt.ranged]:
Richard Smith02e85f32011-04-14 22:09:26 +00001906/// A range-based for statement is equivalent to
1907///
1908/// {
1909/// auto && __range = range-init;
1910/// for ( auto __begin = begin-expr,
1911/// __end = end-expr;
1912/// __begin != __end;
1913/// ++__begin ) {
1914/// for-range-declaration = *__begin;
1915/// statement
1916/// }
1917/// }
1918///
1919/// The body of the loop is not available yet, since it cannot be analysed until
1920/// we have determined the type of the for-range-declaration.
1921StmtResult
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001922Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001923 Stmt *First, SourceLocation ColonLoc, Expr *Range,
Richard Smitha05b3b52012-09-20 21:52:32 +00001924 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith3249fed2013-08-21 01:40:36 +00001925 if (!First)
Richard Smith02e85f32011-04-14 22:09:26 +00001926 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001927
Richard Smith3249fed2013-08-21 01:40:36 +00001928 if (Range && ObjCEnumerationCollection(Range))
Sam Panzer2c4ca0f2012-08-16 21:47:25 +00001929 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001930
1931 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1932 assert(DS && "first part of for range not a decl stmt");
1933
1934 if (!DS->isSingleDecl()) {
1935 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1936 return StmtError();
1937 }
Richard Smith02e85f32011-04-14 22:09:26 +00001938
Richard Smith3249fed2013-08-21 01:40:36 +00001939 Decl *LoopVar = DS->getSingleDecl();
1940 if (LoopVar->isInvalidDecl() || !Range ||
1941 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1942 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001943 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001944 }
Richard Smith02e85f32011-04-14 22:09:26 +00001945
1946 // Build auto && __range = range-init
1947 SourceLocation RangeLoc = Range->getLocStart();
1948 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1949 Context.getAutoRRefDeductType(),
1950 "__range");
1951 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
Richard Smith3249fed2013-08-21 01:40:36 +00001952 diag::err_for_range_deduction_failure)) {
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 // Claim the type doesn't contain auto: we've already done the checking.
1958 DeclGroupPtrTy RangeGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00001959 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
Rafael Espindolaab417692013-07-09 12:05:01 +00001960 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00001961 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
Richard Smith3249fed2013-08-21 01:40:36 +00001962 if (RangeDecl.isInvalid()) {
1963 LoopVar->setInvalidDecl();
Richard Smith02e85f32011-04-14 22:09:26 +00001964 return StmtError();
Richard Smith3249fed2013-08-21 01:40:36 +00001965 }
Richard Smith02e85f32011-04-14 22:09:26 +00001966
1967 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001968 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1969 /*Inc=*/nullptr, DS, RParenLoc, Kind);
Sam Panzer0f384432012-08-21 00:52:01 +00001970}
1971
1972/// \brief Create the initialization, compare, and increment steps for
1973/// the range-based for loop expression.
1974/// This function does not handle array-based for loops,
1975/// which are created in Sema::BuildCXXForRangeStmt.
1976///
1977/// \returns a ForRangeStatus indicating success or what kind of error occurred.
1978/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1979/// CandidateSet and BEF are set and some non-success value is returned on
1980/// failure.
1981static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1982 Expr *BeginRange, Expr *EndRange,
1983 QualType RangeType,
1984 VarDecl *BeginVar,
1985 VarDecl *EndVar,
1986 SourceLocation ColonLoc,
1987 OverloadCandidateSet *CandidateSet,
1988 ExprResult *BeginExpr,
1989 ExprResult *EndExpr,
1990 Sema::BeginEndFunction *BEF) {
1991 DeclarationNameInfo BeginNameInfo(
1992 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1993 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1994 ColonLoc);
1995
1996 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1997 Sema::LookupMemberName);
1998 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1999
2000 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2001 // - if _RangeT is a class type, the unqualified-ids begin and end are
2002 // looked up in the scope of class _RangeT as if by class member access
2003 // lookup (3.4.5), and if either (or both) finds at least one
2004 // declaration, begin-expr and end-expr are __range.begin() and
2005 // __range.end(), respectively;
2006 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2007 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2008
2009 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2010 SourceLocation RangeLoc = BeginVar->getLocation();
2011 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2012
2013 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2014 << RangeLoc << BeginRange->getType() << *BEF;
2015 return Sema::FRS_DiagnosticIssued;
2016 }
2017 } else {
2018 // - otherwise, begin-expr and end-expr are begin(__range) and
2019 // end(__range), respectively, where begin and end are looked up with
2020 // argument-dependent lookup (3.4.2). For the purposes of this name
2021 // lookup, namespace std is an associated namespace.
2022
2023 }
2024
2025 *BEF = Sema::BEF_begin;
2026 Sema::ForRangeStatus RangeStatus =
2027 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2028 Sema::BEF_begin, BeginNameInfo,
2029 BeginMemberLookup, CandidateSet,
2030 BeginRange, BeginExpr);
2031
2032 if (RangeStatus != Sema::FRS_Success)
2033 return RangeStatus;
2034 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2035 diag::err_for_range_iter_deduction_failure)) {
2036 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2037 return Sema::FRS_DiagnosticIssued;
2038 }
2039
2040 *BEF = Sema::BEF_end;
2041 RangeStatus =
2042 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2043 Sema::BEF_end, EndNameInfo,
2044 EndMemberLookup, CandidateSet,
2045 EndRange, EndExpr);
2046 if (RangeStatus != Sema::FRS_Success)
2047 return RangeStatus;
2048 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2049 diag::err_for_range_iter_deduction_failure)) {
2050 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2051 return Sema::FRS_DiagnosticIssued;
2052 }
2053 return Sema::FRS_Success;
2054}
2055
2056/// Speculatively attempt to dereference an invalid range expression.
Richard Smitha05b3b52012-09-20 21:52:32 +00002057/// If the attempt fails, this function will return a valid, null StmtResult
2058/// and emit no diagnostics.
Sam Panzer0f384432012-08-21 00:52:01 +00002059static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2060 SourceLocation ForLoc,
2061 Stmt *LoopVarDecl,
2062 SourceLocation ColonLoc,
2063 Expr *Range,
2064 SourceLocation RangeLoc,
2065 SourceLocation RParenLoc) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002066 // Determine whether we can rebuild the for-range statement with a
2067 // dereferenced range expression.
2068 ExprResult AdjustedRange;
2069 {
2070 Sema::SFINAETrap Trap(SemaRef);
2071
2072 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2073 if (AdjustedRange.isInvalid())
2074 return StmtResult();
2075
2076 StmtResult SR =
2077 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2078 AdjustedRange.get(), RParenLoc,
2079 Sema::BFRK_Check);
2080 if (SR.isInvalid())
2081 return StmtResult();
2082 }
2083
2084 // The attempt to dereference worked well enough that it could produce a valid
2085 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2086 // case there are any other (non-fatal) problems with it.
2087 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2088 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2089 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2090 AdjustedRange.get(), RParenLoc,
2091 Sema::BFRK_Rebuild);
Richard Smith02e85f32011-04-14 22:09:26 +00002092}
2093
Richard Smith3249fed2013-08-21 01:40:36 +00002094namespace {
2095/// RAII object to automatically invalidate a declaration if an error occurs.
2096struct InvalidateOnErrorScope {
2097 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2098 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2099 ~InvalidateOnErrorScope() {
2100 if (Enabled && Trap.hasErrorOccurred())
2101 D->setInvalidDecl();
2102 }
2103
2104 DiagnosticErrorTrap Trap;
2105 Decl *D;
2106 bool Enabled;
2107};
2108}
2109
Richard Smitha05b3b52012-09-20 21:52:32 +00002110/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Richard Smith02e85f32011-04-14 22:09:26 +00002111StmtResult
2112Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2113 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2114 Expr *Inc, Stmt *LoopVarDecl,
Richard Smitha05b3b52012-09-20 21:52:32 +00002115 SourceLocation RParenLoc, BuildForRangeKind Kind) {
Richard Smith02e85f32011-04-14 22:09:26 +00002116 Scope *S = getCurScope();
2117
2118 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2119 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2120 QualType RangeVarType = RangeVar->getType();
2121
2122 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2123 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2124
Richard Smith3249fed2013-08-21 01:40:36 +00002125 // If we hit any errors, mark the loop variable as invalid if its type
2126 // contains 'auto'.
2127 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2128 LoopVar->getType()->isUndeducedType());
2129
Richard Smith02e85f32011-04-14 22:09:26 +00002130 StmtResult BeginEndDecl = BeginEnd;
2131 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2132
Richard Smith27d807c2013-04-30 13:56:41 +00002133 if (RangeVarType->isDependentType()) {
2134 // The range is implicitly used as a placeholder when it is dependent.
Eli Friedman276dd182013-09-05 00:02:25 +00002135 RangeVar->markUsed(Context);
Richard Smith27d807c2013-04-30 13:56:41 +00002136
2137 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2138 // them in properly when we instantiate the loop.
2139 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2140 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2141 } else if (!BeginEndDecl.get()) {
Richard Smith02e85f32011-04-14 22:09:26 +00002142 SourceLocation RangeLoc = RangeVar->getLocation();
2143
Ted Kremenekbed648e2011-10-10 22:36:28 +00002144 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2145
2146 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2147 VK_LValue, ColonLoc);
2148 if (BeginRangeRef.isInvalid())
2149 return StmtError();
2150
2151 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2152 VK_LValue, ColonLoc);
2153 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00002154 return StmtError();
2155
2156 QualType AutoType = Context.getAutoDeductType();
2157 Expr *Range = RangeVar->getInit();
2158 if (!Range)
2159 return StmtError();
2160 QualType RangeType = Range->getType();
2161
2162 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002163 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00002164 return StmtError();
2165
2166 // Build auto __begin = begin-expr, __end = end-expr.
2167 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2168 "__begin");
2169 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2170 "__end");
2171
2172 // Build begin-expr and end-expr and attach to __begin and __end variables.
2173 ExprResult BeginExpr, EndExpr;
2174 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2175 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2176 // __range + __bound, respectively, where __bound is the array bound. If
2177 // _RangeT is an array of unknown size or an array of incomplete type,
2178 // the program is ill-formed;
2179
2180 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002181 BeginExpr = BeginRangeRef;
2182 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00002183 diag::err_for_range_iter_deduction_failure)) {
2184 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2185 return StmtError();
2186 }
2187
2188 // Find the array bound.
2189 ExprResult BoundExpr;
2190 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002191 BoundExpr = IntegerLiteral::Create(
2192 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002193 else if (const VariableArrayType *VAT =
2194 dyn_cast<VariableArrayType>(UnqAT))
2195 BoundExpr = VAT->getSizeExpr();
2196 else {
2197 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2198 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00002199 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00002200 }
2201
2202 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002203 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00002204 BoundExpr.get());
2205 if (EndExpr.isInvalid())
2206 return StmtError();
2207 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2208 diag::err_for_range_iter_deduction_failure)) {
2209 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2210 return StmtError();
2211 }
2212 } else {
Richard Smith100b24a2014-04-17 01:52:14 +00002213 OverloadCandidateSet CandidateSet(RangeLoc,
2214 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +00002215 Sema::BeginEndFunction BEFFailure;
2216 ForRangeStatus RangeStatus =
2217 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2218 EndRangeRef.get(), RangeType,
2219 BeginVar, EndVar, ColonLoc, &CandidateSet,
2220 &BeginExpr, &EndExpr, &BEFFailure);
Richard Smith02e85f32011-04-14 22:09:26 +00002221
Richard Smitha05b3b52012-09-20 21:52:32 +00002222 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
Sam Panzer0f384432012-08-21 00:52:01 +00002223 BEFFailure == BEF_begin) {
Richard Trieu08254692013-10-11 22:16:04 +00002224 // If the range is being built from an array parameter, emit a
2225 // a diagnostic that it is being treated as a pointer.
2226 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2227 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2228 QualType ArrayTy = PVD->getOriginalType();
2229 QualType PointerTy = PVD->getType();
2230 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2231 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2232 << RangeLoc << PVD << ArrayTy << PointerTy;
2233 Diag(PVD->getLocation(), diag::note_declared_at);
2234 return StmtError();
2235 }
2236 }
2237 }
2238
2239 // If building the range failed, try dereferencing the range expression
2240 // unless a diagnostic was issued or the end function is problematic.
Sam Panzer0f384432012-08-21 00:52:01 +00002241 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2242 LoopVarDecl, ColonLoc,
2243 Range, RangeLoc,
2244 RParenLoc);
Richard Smitha05b3b52012-09-20 21:52:32 +00002245 if (SR.isInvalid() || SR.isUsable())
Sam Panzer0f384432012-08-21 00:52:01 +00002246 return SR;
Richard Smith02e85f32011-04-14 22:09:26 +00002247 }
2248
Sam Panzer0f384432012-08-21 00:52:01 +00002249 // Otherwise, emit diagnostics if we haven't already.
2250 if (RangeStatus == FRS_NoViableFunction) {
Richard Smitha05b3b52012-09-20 21:52:32 +00002251 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
Sam Panzer0f384432012-08-21 00:52:01 +00002252 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2253 << RangeLoc << Range->getType() << BEFFailure;
Nico Webera2a0eb92012-12-29 20:03:39 +00002254 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
Sam Panzer0f384432012-08-21 00:52:01 +00002255 }
2256 // Return an error if no fix was discovered.
2257 if (RangeStatus != FRS_Success)
Richard Smith02e85f32011-04-14 22:09:26 +00002258 return StmtError();
2259 }
2260
Sam Panzer0f384432012-08-21 00:52:01 +00002261 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2262 "invalid range expression in for loop");
2263
2264 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
Richard Smith02e85f32011-04-14 22:09:26 +00002265 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2266 if (!Context.hasSameType(BeginType, EndType)) {
2267 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2268 << BeginType << EndType;
2269 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2270 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2271 }
2272
2273 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2274 // Claim the type doesn't contain auto: we've already done the checking.
2275 DeclGroupPtrTy BeginEndGroup =
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00002276 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
Rafael Espindolaab417692013-07-09 12:05:01 +00002277 /*TypeMayContainAuto=*/ false);
Richard Smith02e85f32011-04-14 22:09:26 +00002278 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2279
Ted Kremenekbed648e2011-10-10 22:36:28 +00002280 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2281 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00002282 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002283 if (BeginRef.isInvalid())
2284 return StmtError();
2285
Richard Smith02e85f32011-04-14 22:09:26 +00002286 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2287 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00002288 if (EndRef.isInvalid())
2289 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00002290
2291 // Build and check __begin != __end expression.
2292 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2293 BeginRef.get(), EndRef.get());
2294 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2295 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2296 if (NotEqExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002297 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2298 << RangeLoc << 0 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002299 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2300 if (!Context.hasSameType(BeginType, EndType))
2301 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2302 return StmtError();
2303 }
2304
2305 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002306 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2307 VK_LValue, ColonLoc);
2308 if (BeginRef.isInvalid())
2309 return StmtError();
2310
Richard Smith02e85f32011-04-14 22:09:26 +00002311 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2312 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2313 if (IncrExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002314 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2315 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
Richard Smith02e85f32011-04-14 22:09:26 +00002316 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2317 return StmtError();
2318 }
2319
2320 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00002321 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2322 VK_LValue, ColonLoc);
2323 if (BeginRef.isInvalid())
2324 return StmtError();
2325
Richard Smith02e85f32011-04-14 22:09:26 +00002326 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2327 if (DerefExpr.isInvalid()) {
Sam Panzer22a3fe12012-09-06 21:50:08 +00002328 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2329 << RangeLoc << 1 << BeginRangeRef.get()->getType();
Richard Smith02e85f32011-04-14 22:09:26 +00002330 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2331 return StmtError();
2332 }
2333
Richard Smitha05b3b52012-09-20 21:52:32 +00002334 // Attach *__begin as initializer for VD. Don't touch it if we're just
2335 // trying to determine whether this would be a valid range.
2336 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
Richard Smith02e85f32011-04-14 22:09:26 +00002337 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2338 /*TypeMayContainAuto=*/true);
2339 if (LoopVar->isInvalidDecl())
2340 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2341 }
2342 }
2343
Richard Smitha05b3b52012-09-20 21:52:32 +00002344 // Don't bother to actually allocate the result if we're just trying to
2345 // determine whether it would be valid.
2346 if (Kind == BFRK_Check)
2347 return StmtResult();
2348
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002349 return new (Context) CXXForRangeStmt(
2350 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2351 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00002352}
2353
Chad Rosier02a84392012-08-10 17:56:09 +00002354/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002355/// statement.
2356StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2357 if (!S || !B)
2358 return StmtError();
2359 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00002360
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00002361 ForStmt->setBody(B);
2362 return S;
2363}
2364
Richard Smith02e85f32011-04-14 22:09:26 +00002365/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2366/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2367/// body cannot be performed until after the type of the range variable is
2368/// determined.
2369StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2370 if (!S || !B)
2371 return StmtError();
2372
Fariborz Jahanian00213472012-07-06 19:04:04 +00002373 if (isa<ObjCForCollectionStmt>(S))
2374 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002375
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002376 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2377 ForStmt->setBody(B);
2378
2379 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2380 diag::warn_empty_range_based_for_body);
2381
Richard Smith02e85f32011-04-14 22:09:26 +00002382 return S;
2383}
2384
Chris Lattnercab02a62011-02-17 20:34:02 +00002385StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2386 SourceLocation LabelLoc,
2387 LabelDecl *TheDecl) {
2388 getCurFunction()->setHasBranchIntoScope();
Eli Friedman276dd182013-09-05 00:02:25 +00002389 TheDecl->markUsed(Context);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002390 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002391}
Chris Lattner1c310502007-05-31 06:00:00 +00002392
John McCalldadc5752010-08-24 06:29:42 +00002393StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002394Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002395 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002396 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002397 if (!E->isTypeDependent()) {
2398 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002399 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002400 ExprResult ExprRes = E;
Douglas Gregor30776d42009-05-16 00:20:29 +00002401 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002402 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2403 if (ExprRes.isInvalid())
2404 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002405 E = ExprRes.get();
Chandler Carruth00216982010-01-31 10:26:25 +00002406 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002407 return StmtError();
2408 }
John McCalla95172b2010-08-01 00:26:45 +00002409
Richard Smith945f8d32013-01-14 22:39:08 +00002410 ExprResult ExprRes = ActOnFinishFullExpr(E);
2411 if (ExprRes.isInvalid())
2412 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002413 E = ExprRes.get();
Richard Smith945f8d32013-01-14 22:39:08 +00002414
John McCallaab3e412010-08-25 08:40:02 +00002415 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002416
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002417 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002418}
2419
Nico Weberd64657f2015-03-09 02:47:59 +00002420static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2421 const Scope &DestScope) {
2422 if (!S.CurrentSEHFinally.empty() &&
2423 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2424 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2425 }
2426}
2427
John McCalldadc5752010-08-24 06:29:42 +00002428StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002429Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002430 Scope *S = CurScope->getContinueParent();
2431 if (!S) {
2432 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002433 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002434 }
Nico Weberd64657f2015-03-09 02:47:59 +00002435 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002436
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002437 return new (Context) ContinueStmt(ContinueLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002438}
2439
John McCalldadc5752010-08-24 06:29:42 +00002440StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002441Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002442 Scope *S = CurScope->getBreakParent();
2443 if (!S) {
2444 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002445 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002446 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002447 if (S->isOpenMPLoopScope())
2448 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2449 << "break");
Nico Weberd64657f2015-03-09 02:47:59 +00002450 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
Sebastian Redl573feed2009-01-18 13:19:59 +00002451
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002452 return new (Context) BreakStmt(BreakLoc);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002453}
2454
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002456/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002457///
Douglas Gregor5d369002011-01-21 18:05:27 +00002458/// \param ReturnType If we're determining the copy elision candidate for
2459/// a return statement, this is the return type of the function. If we're
2460/// determining the copy elision candidate for a throw expression, this will
2461/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002462///
Douglas Gregor5d369002011-01-21 18:05:27 +00002463/// \param E The expression being returned from the function or block, or
2464/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002465///
Douglas Gregor86394412011-05-20 15:00:53 +00002466/// \param AllowFunctionParameter Whether we allow function parameters to
2467/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2468/// we re-use this logic to determine whether we should try to move as part of
2469/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002470///
2471/// \returns The NRVO candidate variable, if the return statement may use the
2472/// NRVO, or NULL if there is no such candidate.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002473VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2474 Expr *E,
2475 bool AllowFunctionParameter) {
2476 if (!getLangOpts().CPlusPlus)
2477 return nullptr;
2478
2479 // - in a return statement in a function [where] ...
2480 // ... the expression is the name of a non-volatile automatic object ...
2481 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002482 if (!DR || DR->refersToEnclosingVariableOrCapture())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002483 return nullptr;
2484 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2485 if (!VD)
2486 return nullptr;
2487
2488 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2489 return VD;
2490 return nullptr;
2491}
2492
2493bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2494 bool AllowFunctionParameter) {
2495 QualType VDType = VD->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002496 // - in a return statement in a function with ...
2497 // ... a class return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002498 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
Douglas Gregor5d369002011-01-21 18:05:27 +00002499 if (!ReturnType->isRecordType())
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002500 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002501 // ... the same cv-unqualified type as the function return type ...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002502 if (!VDType->isDependentType() &&
2503 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2504 return false;
Douglas Gregor5d369002011-01-21 18:05:27 +00002505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506
John McCall03318c12011-11-11 03:57:31 +00002507 // ...object (other than a function or catch-clause parameter)...
2508 if (VD->getKind() != Decl::Var &&
2509 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002510 return false;
2511 if (VD->isExceptionVariable()) return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512
John McCall03318c12011-11-11 03:57:31 +00002513 // ...automatic...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002514 if (!VD->hasLocalStorage()) return false;
John McCall03318c12011-11-11 03:57:31 +00002515
2516 // ...non-volatile...
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002517 if (VD->getType().isVolatileQualified()) return false;
John McCall03318c12011-11-11 03:57:31 +00002518
2519 // __block variables can't be allocated in a way that permits NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002520 if (VD->hasAttr<BlocksAttr>()) return false;
John McCall03318c12011-11-11 03:57:31 +00002521
2522 // Variables with higher required alignment than their type's ABI
2523 // alignment cannot use NRVO.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002524 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
John McCall03318c12011-11-11 03:57:31 +00002525 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002526 return false;
John McCall03318c12011-11-11 03:57:31 +00002527
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002528 return true;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002529}
2530
Douglas Gregor626fbed2011-01-21 21:08:57 +00002531/// \brief Perform the initialization of a potentially-movable value, which
2532/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002533///
2534/// This routine implements C++0x [class.copy]p33, which attempts to treat
2535/// returned lvalues as rvalues in certain cases (to prefer move construction),
2536/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002537ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002538Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2539 const VarDecl *NRVOCandidate,
2540 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002541 Expr *Value,
2542 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002543 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002544 // When the criteria for elision of a copy operation are met or would
2545 // be met save for the fact that the source object is a function
2546 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002547 // overload resolution to select the constructor for the copy is first
2548 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002549 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002550 if (AllowNRVO &&
2551 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002552 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002553 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554
Douglas Gregorf282a762011-01-21 19:38:21 +00002555 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002556 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002557 = InitializationKind::CreateCopy(Value->getLocStart(),
2558 Value->getLocStart());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002559 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560
2561 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002562 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002563 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002564 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002565 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002566 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2567 StepEnd = Seq.step_end();
2568 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002569 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002570 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002571
2572 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002573 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574
Douglas Gregorf282a762011-01-21 19:38:21 +00002575 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002576 = Constructor->getParamDecl(0)->getType()
2577 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002578
Douglas Gregorf282a762011-01-21 19:38:21 +00002579 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002581 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2582 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002584
Douglas Gregorf282a762011-01-21 19:38:21 +00002585 // Promote "AsRvalue" to the heap, since we now need this
2586 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002587 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002588 CK_NoOp, Value, nullptr, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589
Douglas Gregorf282a762011-01-21 19:38:21 +00002590 // Complete type-checking the initialization of the return type
2591 // using the constructor we found.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002592 Res = Seq.Perform(*this, Entity, Kind, Value);
Douglas Gregorf282a762011-01-21 19:38:21 +00002593 }
2594 }
2595 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002596
Douglas Gregorf282a762011-01-21 19:38:21 +00002597 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002598 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002599 // (again) now with the return value expression as written.
2600 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002601 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002602
Douglas Gregorf282a762011-01-21 19:38:21 +00002603 return Res;
2604}
2605
Richard Smith4db51c22013-09-25 05:02:54 +00002606/// \brief Determine whether the declared return type of the specified function
2607/// contains 'auto'.
2608static bool hasDeducedReturnType(FunctionDecl *FD) {
2609 const FunctionProtoType *FPT =
2610 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002611 return FPT->getReturnType()->isUndeducedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002612}
2613
Eli Friedman34b49062012-01-26 03:00:14 +00002614/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2615/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002616///
John McCalldadc5752010-08-24 06:29:42 +00002617StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002618Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2619 // If this is the first return we've seen, infer the return type.
Richard Smith9155be12013-05-12 03:09:35 +00002620 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
Eli Friedman34b49062012-01-26 03:00:14 +00002621 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002622 QualType FnRetType = CurCap->ReturnType;
Richard Smith4db51c22013-09-25 05:02:54 +00002623 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002624
Richard Smith4db51c22013-09-25 05:02:54 +00002625 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2626 // In C++1y, the return type may involve 'auto'.
2627 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2628 FunctionDecl *FD = CurLambda->CallOperator;
2629 if (CurCap->ReturnType.isNull())
Alp Toker314cc812014-01-25 16:55:45 +00002630 CurCap->ReturnType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002631
2632 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2633 assert(AT && "lost auto type from lambda return type");
2634 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2635 FD->setInvalidDecl();
2636 return StmtError();
2637 }
Alp Toker314cc812014-01-25 16:55:45 +00002638 CurCap->ReturnType = FnRetType = FD->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +00002639 } else if (CurCap->HasImplicitReturnType) {
2640 // For blocks/lambdas with implicit return types, we check each return
2641 // statement individually, and deduce the common return type when the block
2642 // or lambda is completed.
2643 // FIXME: Fold this into the 'auto' codepath above.
Douglas Gregor940a5502012-02-09 18:40:39 +00002644 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002645 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2646 if (Result.isInvalid())
2647 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002648 RetValExp = Result.get();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002649
Richard Smith5a0e50c2014-12-19 22:10:51 +00002650 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2651 // when deducing a return type for a lambda-expression (or by extension
2652 // for a block). These rules differ from the stated C++11 rules only in
2653 // that they remove top-level cv-qualifiers.
Richard Smith4db51c22013-09-25 05:02:54 +00002654 if (!CurContext->isDependentContext())
Richard Smith5a0e50c2014-12-19 22:10:51 +00002655 FnRetType = RetValExp->getType().getUnqualifiedType();
Richard Smith4db51c22013-09-25 05:02:54 +00002656 else
Jordan Rosed39e5f12012-07-02 21:19:23 +00002657 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002658 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002659 if (RetValExp) {
2660 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2661 // initializer list, because it is not an expression (even
2662 // though we represent it as one). We still deduce 'void'.
2663 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2664 << RetValExp->getSourceRange();
2665 }
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002666
Jordan Rosed39e5f12012-07-02 21:19:23 +00002667 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002668 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002669
2670 // Although we'll properly infer the type of the block once it's completed,
2671 // make sure we provide a return type now for better error recovery.
2672 if (CurCap->ReturnType.isNull())
2673 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002674 }
Eli Friedman34b49062012-01-26 03:00:14 +00002675 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002676
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002677 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002678 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2679 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2680 return StmtError();
2681 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00002682 } else if (CapturedRegionScopeInfo *CurRegion =
2683 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2684 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2685 return StmtError();
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002686 } else {
Richard Smith4db51c22013-09-25 05:02:54 +00002687 assert(CurLambda && "unknown kind of captured scope");
2688 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2689 ->getNoReturnAttr()) {
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002690 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2691 return StmtError();
2692 }
2693 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002694
Steve Naroffc540d662008-09-03 18:15:37 +00002695 // Otherwise, verify that this result type matches the previous one. We are
2696 // pickier with blocks than for normal functions because we don't have GCC
2697 // compatibility to worry about here.
Craig Topperc3ec1492014-05-26 06:22:03 +00002698 const VarDecl *NRVOCandidate = nullptr;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002699 if (FnRetType->isDependentType()) {
John McCall5500ef22011-08-17 22:09:46 +00002700 // Delay processing for now. TODO: there are lots of dependent
2701 // types we can conclusively prove aren't void.
2702 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002703 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002704 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002705 (RetValExp->isTypeDependent() ||
2706 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002707 if (!getLangOpts().CPlusPlus &&
2708 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002709 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002710 else {
2711 Diag(ReturnLoc, diag::err_return_block_has_expr);
Craig Topperc3ec1492014-05-26 06:22:03 +00002712 RetValExp = nullptr;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002713 }
Steve Naroffc540d662008-09-03 18:15:37 +00002714 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002715 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002716 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2717 } else if (!RetValExp->isTypeDependent()) {
2718 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002719
John McCall5500ef22011-08-17 22:09:46 +00002720 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2721 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2722 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002723
John McCall5500ef22011-08-17 22:09:46 +00002724 // In C++ the return statement is handled via a copy initialization.
2725 // the C version of which boils down to CheckSingleAssignmentConstraints.
2726 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2727 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2728 FnRetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002729 NRVOCandidate != nullptr);
John McCall5500ef22011-08-17 22:09:46 +00002730 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2731 FnRetType, RetValExp);
2732 if (Res.isInvalid()) {
2733 // FIXME: Cleanup temporaries here, anyway?
2734 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002735 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002736 RetValExp = Res.get();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002737 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002738 } else {
2739 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Steve Naroffc540d662008-09-03 18:15:37 +00002740 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002741
John McCall75f92b52011-08-17 21:34:14 +00002742 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00002743 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2744 if (ER.isInvalid())
2745 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002746 RetValExp = ER.get();
John McCall75f92b52011-08-17 21:34:14 +00002747 }
John McCall5500ef22011-08-17 22:09:46 +00002748 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2749 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002750
Jordan Rosed39e5f12012-07-02 21:19:23 +00002751 // If we need to check for the named return value optimization,
2752 // or if we need to infer the return type,
2753 // save the return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002754 if (CurCap->HasImplicitReturnType || NRVOCandidate)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002755 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002756
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002757 return Result;
Steve Naroffc540d662008-09-03 18:15:37 +00002758}
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002759
Nico Weber72889432014-09-06 01:25:55 +00002760namespace {
2761/// \brief Marks all typedefs in all local classes in a type referenced.
2762///
2763/// In a function like
2764/// auto f() {
2765/// struct S { typedef int a; };
2766/// return S();
2767/// }
2768///
2769/// the local type escapes and could be referenced in some TUs but not in
2770/// others. Pretend that all local typedefs are always referenced, to not warn
2771/// on this. This isn't necessary if f has internal linkage, or the typedef
2772/// is private.
2773class LocalTypedefNameReferencer
2774 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2775public:
2776 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2777 bool VisitRecordType(const RecordType *RT);
2778private:
2779 Sema &S;
2780};
2781bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2782 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2783 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2784 R->isDependentType())
2785 return true;
2786 for (auto *TmpD : R->decls())
2787 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2788 if (T->getAccess() != AS_private || R->hasFriends())
2789 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2790 return true;
2791}
2792}
2793
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002794TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002795 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002796 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2797 TL = ATL.getModifiedLoc().IgnoreParens();
Saleem Abdulrasoole8aab742014-10-17 17:20:33 +00002798 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002799}
2800
Richard Smith2a7d4812013-05-04 07:00:32 +00002801/// Deduce the return type for a function from a returned expression, per
2802/// C++1y [dcl.spec.auto]p6.
2803bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2804 SourceLocation ReturnLoc,
2805 Expr *&RetExpr,
2806 AutoType *AT) {
Saleem Abdulrasool374b5aa2014-10-16 22:42:53 +00002807 TypeLoc OrigResultType = getReturnTypeLoc(FD);
Richard Smith2a7d4812013-05-04 07:00:32 +00002808 QualType Deduced;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002809
Richard Smithc58f38f2013-08-14 20:16:31 +00002810 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2811 // If the deduction is for a return statement and the initializer is
2812 // a braced-init-list, the program is ill-formed.
Richard Smith4db51c22013-09-25 05:02:54 +00002813 Diag(RetExpr->getExprLoc(),
2814 getCurLambda() ? diag::err_lambda_return_init_list
2815 : diag::err_auto_fn_return_init_list)
2816 << RetExpr->getSourceRange();
Richard Smithc58f38f2013-08-14 20:16:31 +00002817 return true;
2818 }
2819
2820 if (FD->isDependentContext()) {
2821 // C++1y [dcl.spec.auto]p12:
2822 // Return type deduction [...] occurs when the definition is
2823 // instantiated even if the function body contains a return
2824 // statement with a non-type-dependent operand.
2825 assert(AT->isDeduced() && "should have deduced to dependent type");
2826 return false;
2827 } else if (RetExpr) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002828 // If the deduction is for a return statement and the initializer is
2829 // a braced-init-list, the program is ill-formed.
2830 if (isa<InitListExpr>(RetExpr)) {
2831 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2832 return true;
2833 }
2834
2835 // Otherwise, [...] deduce a value for U using the rules of template
2836 // argument deduction.
2837 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2838
2839 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2840 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2841 << OrigResultType.getType() << RetExpr->getType();
2842
2843 if (DAR != DAR_Succeeded)
2844 return true;
Nico Weber72889432014-09-06 01:25:55 +00002845
2846 // If a local type is part of the returned type, mark its fields as
2847 // referenced.
2848 LocalTypedefNameReferencer Referencer(*this);
2849 Referencer.TraverseType(RetExpr->getType());
Richard Smith2a7d4812013-05-04 07:00:32 +00002850 } else {
2851 // In the case of a return with no operand, the initializer is considered
2852 // to be void().
2853 //
2854 // Deduction here can only succeed if the return type is exactly 'cv auto'
2855 // or 'decltype(auto)', so just check for that case directly.
2856 if (!OrigResultType.getType()->getAs<AutoType>()) {
2857 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2858 << OrigResultType.getType();
2859 return true;
2860 }
2861 // We always deduce U = void in this case.
2862 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2863 if (Deduced.isNull())
2864 return true;
2865 }
2866
2867 // If a function with a declared return type that contains a placeholder type
2868 // has multiple return statements, the return type is deduced for each return
2869 // statement. [...] if the type deduced is not the same in each deduction,
2870 // the program is ill-formed.
2871 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2872 AutoType *NewAT = Deduced->getContainedAutoType();
Richard Smithc58f38f2013-08-14 20:16:31 +00002873 if (!FD->isDependentContext() &&
2874 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
Richard Smith4db51c22013-09-25 05:02:54 +00002875 const LambdaScopeInfo *LambdaSI = getCurLambda();
2876 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2877 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2878 << NewAT->getDeducedType() << AT->getDeducedType()
2879 << true /*IsLambda*/;
2880 } else {
2881 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2882 << (AT->isDecltypeAuto() ? 1 : 0)
2883 << NewAT->getDeducedType() << AT->getDeducedType();
2884 }
Richard Smith2a7d4812013-05-04 07:00:32 +00002885 return true;
2886 }
2887 } else if (!FD->isInvalidDecl()) {
2888 // Update all declarations of the function to have the deduced return type.
2889 Context.adjustDeducedFunctionResultType(FD, Deduced);
2890 }
2891
2892 return false;
2893}
2894
John McCalldadc5752010-08-24 06:29:42 +00002895StmtResult
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002896Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2897 Scope *CurScope) {
2898 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2899 if (R.isInvalid()) {
2900 return R;
2901 }
2902
2903 if (VarDecl *VD =
2904 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2905 CurScope->addNRVOCandidate(VD);
2906 } else {
2907 CurScope->setNoNRVO();
2908 }
2909
Nico Weberd64657f2015-03-09 02:47:59 +00002910 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
2911
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00002912 return R;
2913}
2914
2915StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002916 // Check for unexpanded parameter packs.
2917 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2918 return StmtError();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002919
Eli Friedman34b49062012-01-26 03:00:14 +00002920 if (isa<CapturingScopeInfo>(getCurFunction()))
2921 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Manuel Klimek2fdbea22013-08-22 12:12:24 +00002922
Chris Lattner79413952008-12-04 23:50:19 +00002923 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002924 QualType RelatedRetType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002925 const AttrVec *Attrs = nullptr;
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002926 bool isObjCMethod = false;
2927
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002928 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002929 FnRetType = FD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002930 if (FD->hasAttrs())
2931 Attrs = &FD->getAttrs();
Richard Smith10876ef2013-01-17 01:30:42 +00002932 if (FD->isNoReturn())
Chris Lattner6e127a62009-05-31 19:32:13 +00002933 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002934 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002935 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002936 FnRetType = MD->getReturnType();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002937 isObjCMethod = true;
2938 if (MD->hasAttrs())
2939 Attrs = &MD->getAttrs();
Douglas Gregor33823722011-06-11 01:09:30 +00002940 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2941 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002942 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002943 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002944 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2945 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002946 }
2947 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002948 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002949
Richard Smith2a7d4812013-05-04 07:00:32 +00002950 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2951 // deduction.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002952 if (getLangOpts().CPlusPlus14) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002953 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2954 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
Richard Smithc58f38f2013-08-14 20:16:31 +00002955 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002956 FD->setInvalidDecl();
2957 return StmtError();
2958 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002959 FnRetType = FD->getReturnType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002960 }
2961 }
2962 }
2963
Richard Smithc58f38f2013-08-14 20:16:31 +00002964 bool HasDependentReturnType = FnRetType->isDependentType();
2965
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 ReturnStmt *Result = nullptr;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002967 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002968 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002969 if (isa<InitListExpr>(RetValExp)) {
2970 // We simply never allow init lists as the return value of void
2971 // functions. This is compatible because this was never allowed before,
2972 // so there's no legacy code to deal with.
2973 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2974 int FunctionKind = 0;
2975 if (isa<ObjCMethodDecl>(CurDecl))
2976 FunctionKind = 1;
2977 else if (isa<CXXConstructorDecl>(CurDecl))
2978 FunctionKind = 2;
2979 else if (isa<CXXDestructorDecl>(CurDecl))
2980 FunctionKind = 3;
2981
2982 Diag(ReturnLoc, diag::err_return_init_list)
2983 << CurDecl->getDeclName() << FunctionKind
2984 << RetValExp->getSourceRange();
2985
2986 // Drop the expression.
Craig Topperc3ec1492014-05-26 06:22:03 +00002987 RetValExp = nullptr;
Sebastian Redleef474c2012-02-22 10:50:08 +00002988 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002989 // C99 6.8.6.4p1 (ext_ since GCC warns)
2990 unsigned D = diag::ext_return_has_expr;
Fariborz Jahaniana7598482013-12-03 17:10:08 +00002991 if (RetValExp->getType()->isVoidType()) {
2992 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2993 if (isa<CXXConstructorDecl>(CurDecl) ||
2994 isa<CXXDestructorDecl>(CurDecl))
2995 D = diag::err_ctor_dtor_returns_void;
2996 else
2997 D = diag::ext_return_has_void_expr;
2998 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00002999 else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003000 ExprResult Result = RetValExp;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003001 Result = IgnoredValueConversions(Result.get());
Nick Lewycky1be750a2011-06-01 07:44:31 +00003002 if (Result.isInvalid())
3003 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 RetValExp = Result.get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003005 RetValExp = ImpCastExprToType(RetValExp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003006 Context.VoidTy, CK_ToVoid).get();
Nick Lewycky1be750a2011-06-01 07:44:31 +00003007 }
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003008 // return of void in constructor/destructor is illegal in C++.
3009 if (D == diag::err_ctor_dtor_returns_void) {
3010 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3011 Diag(ReturnLoc, D)
3012 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3013 << RetValExp->getSourceRange();
3014 }
Nick Lewycky1be750a2011-06-01 07:44:31 +00003015 // return (some void expression); is legal in C++.
Fariborz Jahaniana7598482013-12-03 17:10:08 +00003016 else if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003017 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00003018 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003019
3020 int FunctionKind = 0;
3021 if (isa<ObjCMethodDecl>(CurDecl))
3022 FunctionKind = 1;
3023 else if (isa<CXXConstructorDecl>(CurDecl))
3024 FunctionKind = 2;
3025 else if (isa<CXXDestructorDecl>(CurDecl))
3026 FunctionKind = 3;
3027
Nick Lewycky1be750a2011-06-01 07:44:31 +00003028 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00003029 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00003030 << RetValExp->getSourceRange();
3031 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00003032 }
Mike Stump11289f42009-09-09 15:08:12 +00003033
Sebastian Redleef474c2012-02-22 10:50:08 +00003034 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003035 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3036 if (ER.isInvalid())
3037 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003038 RetValExp = ER.get();
Sebastian Redleef474c2012-02-22 10:50:08 +00003039 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00003040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003041
Craig Topperc3ec1492014-05-26 06:22:03 +00003042 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
Richard Smith2a7d4812013-05-04 07:00:32 +00003043 } else if (!RetValExp && !HasDependentReturnType) {
David Majnemer2887ad32014-12-13 08:12:56 +00003044 FunctionDecl *FD = getCurFunctionDecl();
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003045
David Majnemer2887ad32014-12-13 08:12:56 +00003046 unsigned DiagID;
3047 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3048 // C++11 [stmt.return]p2
3049 DiagID = diag::err_constexpr_return_missing_expr;
3050 FD->setInvalidDecl();
3051 } else if (getLangOpts().C99) {
3052 // C99 6.8.6.4p1 (ext_ since GCC warns)
3053 DiagID = diag::ext_return_missing_expr;
3054 } else {
3055 // C90 6.6.6.4p4
3056 DiagID = diag::warn_return_missing_expr;
3057 }
3058
3059 if (FD)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003060 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003061 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00003062 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
David Majnemer2887ad32014-12-13 08:12:56 +00003063
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003064 Result = new (Context) ReturnStmt(ReturnLoc);
3065 } else {
Richard Smith2a7d4812013-05-04 07:00:32 +00003066 assert(RetValExp || HasDependentReturnType);
Craig Topperc3ec1492014-05-26 06:22:03 +00003067 const VarDecl *NRVOCandidate = nullptr;
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003068
3069 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3070
3071 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3072 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3073 // function return.
3074
3075 // In C++ the return statement is handled via a copy initialization,
3076 // the C version of which boils down to CheckSingleAssignmentConstraints.
3077 if (RetValExp)
3078 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
Richard Smith2a7d4812013-05-04 07:00:32 +00003079 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003080 // we have a non-void function with an expression, continue checking
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
John McCall5ec7e7d2013-03-19 07:04:25 +00003082 RetType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003083 NRVOCandidate != nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
John McCall5ec7e7d2013-03-19 07:04:25 +00003085 RetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003086 if (Res.isInvalid()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00003087 // FIXME: Clean up temporaries here anyway?
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003088 return StmtError();
3089 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003090 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003091
3092 // If we have a related result type, we need to implicitly
3093 // convert back to the formal result type. We can't pretend to
3094 // initialize the result again --- we might end double-retaining
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003095 // --- so instead we initialize a notional temporary.
John McCall5ec7e7d2013-03-19 07:04:25 +00003096 if (!RelatedRetType.isNull()) {
Fariborz Jahanianb248ca52013-07-11 16:48:06 +00003097 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3098 FnRetType);
John McCall5ec7e7d2013-03-19 07:04:25 +00003099 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3100 if (Res.isInvalid()) {
3101 // FIXME: Clean up temporaries here anyway?
3102 return StmtError();
3103 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003104 RetValExp = Res.getAs<Expr>();
John McCall5ec7e7d2013-03-19 07:04:25 +00003105 }
3106
Artyom Skrobov9f213442014-01-24 11:10:39 +00003107 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3108 getCurFunctionDecl());
Douglas Gregorffe14e32009-11-14 01:20:54 +00003109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110
John McCallacf0ee52010-10-08 02:01:28 +00003111 if (RetValExp) {
Richard Smith945f8d32013-01-14 22:39:08 +00003112 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3113 if (ER.isInvalid())
3114 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003115 RetValExp = ER.get();
John McCallacf0ee52010-10-08 02:01:28 +00003116 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003117 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00003118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003119
3120 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003121 // return statement in our scope for later processing.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00003122 if (Result->getNRVOCandidate())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00003123 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00003124
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003125 return Result;
Chris Lattneraf8d5812006-11-10 05:07:45 +00003126}
3127
John McCalldadc5752010-08-24 06:29:42 +00003128StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003129Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003130 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003131 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003132 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003133 if (Var && Var->isInvalidDecl())
3134 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003136 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003137}
3138
John McCalldadc5752010-08-24 06:29:42 +00003139StmtResult
John McCallb268a282010-08-23 23:25:46 +00003140Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003141 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003142}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003143
John McCalldadc5752010-08-24 06:29:42 +00003144StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003146 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003147 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003148 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3149
John McCallaab3e412010-08-25 08:40:02 +00003150 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003151 unsigned NumCatchStmts = CatchStmts.size();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003152 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3153 NumCatchStmts, Finally);
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003154}
3155
John McCall0bd3e402012-05-08 21:41:25 +00003156StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003157 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003158 ExprResult Result = DefaultLvalueConversion(Throw);
3159 if (Result.isInvalid())
3160 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003161
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003162 Result = ActOnFinishFullExpr(Result.get());
Richard Smith945f8d32013-01-14 22:39:08 +00003163 if (Result.isInvalid())
3164 return StmtError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003165 Throw = Result.get();
Richard Smith945f8d32013-01-14 22:39:08 +00003166
Douglas Gregor2900c162010-04-22 21:44:01 +00003167 QualType ThrowType = Throw->getType();
3168 // Make sure the expression type is an ObjC pointer or "void *".
3169 if (!ThrowType->isDependentType() &&
3170 !ThrowType->isObjCObjectPointerType()) {
3171 const PointerType *PT = ThrowType->getAs<PointerType>();
3172 if (!PT || !PT->getPointeeType()->isVoidType())
3173 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3174 << Throw->getType() << Throw->getSourceRange());
3175 }
3176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003178 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
Douglas Gregor2900c162010-04-22 21:44:01 +00003179}
3180
John McCalldadc5752010-08-24 06:29:42 +00003181StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003183 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003184 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003185 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3186
John McCallb268a282010-08-23 23:25:46 +00003187 if (!Throw) {
Nico Weber9af63b22015-03-09 02:34:29 +00003188 // @throw without an expression designates a rethrow (which must occur
Steve Naroff5ee2c022009-02-11 20:05:44 +00003189 // in the context of an @catch clause).
3190 Scope *AtCatchParent = CurScope;
3191 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3192 AtCatchParent = AtCatchParent->getParent();
3193 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003194 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003195 }
John McCallb268a282010-08-23 23:25:46 +00003196 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003197}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003198
John McCalld9bb7432011-07-27 21:50:02 +00003199ExprResult
3200Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3201 ExprResult result = DefaultLvalueConversion(operand);
3202 if (result.isInvalid())
3203 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003204 operand = result.get();
John McCalld9bb7432011-07-27 21:50:02 +00003205
3206 // Make sure the expression type is an ObjC pointer or "void *".
3207 QualType type = operand->getType();
3208 if (!type->isDependentType() &&
3209 !type->isObjCObjectPointerType()) {
3210 const PointerType *pointerType = type->getAs<PointerType>();
Jordan Rose5790d522014-08-12 16:20:36 +00003211 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3212 if (getLangOpts().CPlusPlus) {
3213 if (RequireCompleteType(atLoc, type,
3214 diag::err_incomplete_receiver_type))
3215 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3216 << type << operand->getSourceRange();
3217
3218 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3219 if (!result.isUsable())
3220 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3221 << type << operand->getSourceRange();
3222
3223 operand = result.get();
3224 } else {
3225 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3226 << type << operand->getSourceRange();
3227 }
3228 }
John McCalld9bb7432011-07-27 21:50:02 +00003229 }
3230
3231 // The operand to @synchronized is a full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003232 return ActOnFinishFullExpr(operand);
John McCalld9bb7432011-07-27 21:50:02 +00003233}
3234
John McCalldadc5752010-08-24 06:29:42 +00003235StmtResult
John McCallb268a282010-08-23 23:25:46 +00003236Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3237 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003238 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003239 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003240 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003241}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003242
3243/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3244/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003245StmtResult
John McCall48871652010-08-21 09:40:31 +00003246Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003247 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003248 // There's nothing to test that ActOnExceptionDecl didn't already test.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003249 return new (Context)
3250 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
Sebastian Redl54c04d42008-12-22 19:15:10 +00003251}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003252
John McCall31168b02011-06-15 23:02:42 +00003253StmtResult
3254Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3255 getCurFunction()->setHasBranchProtectedScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003256 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
John McCall31168b02011-06-15 23:02:42 +00003257}
3258
Aaron Ballman8aee642902015-04-08 00:05:29 +00003259class CatchHandlerType {
3260 QualType QT;
3261 unsigned IsPointer : 1;
Dan Gohman28ade552010-07-26 21:25:24 +00003262
Aaron Ballman8aee642902015-04-08 00:05:29 +00003263 // This is a special constructor to be used only with DenseMapInfo's
3264 // getEmptyKey() and getTombstoneKey() functions.
3265 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3266 enum Unique { ForDenseMap };
3267 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3268
Sebastian Redl63c4da02009-07-29 17:15:45 +00003269public:
Aaron Ballman8aee642902015-04-08 00:05:29 +00003270 /// Used when creating a CatchHandlerType from a handler type; will determine
3271 /// whether the type is a pointer or reference and will strip off the the top
3272 /// level pointer and cv-qualifiers.
3273 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3274 if (QT->isPointerType())
3275 IsPointer = true;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003276
Aaron Ballman8aee642902015-04-08 00:05:29 +00003277 if (IsPointer || QT->isReferenceType())
3278 QT = QT->getPointeeType();
3279 QT = QT.getUnqualifiedType();
3280 }
3281
3282 /// Used when creating a CatchHandlerType from a base class type; pretends the
3283 /// type passed in had the pointer qualifier, does not need to get an
3284 /// unqualified type.
3285 CatchHandlerType(QualType QT, bool IsPointer)
3286 : QT(QT), IsPointer(IsPointer) {}
3287
3288 QualType underlying() const { return QT; }
3289 bool isPointer() const { return IsPointer; }
3290
3291 friend bool operator==(const CatchHandlerType &LHS,
3292 const CatchHandlerType &RHS) {
3293 // If the pointer qualification does not match, we can return early.
3294 if (LHS.IsPointer != RHS.IsPointer)
Sebastian Redl63c4da02009-07-29 17:15:45 +00003295 return false;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003296 // Otherwise, check the underlying type without cv-qualifiers.
3297 return LHS.QT == RHS.QT;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003298 }
3299};
3300
Aaron Ballman8aee642902015-04-08 00:05:29 +00003301namespace llvm {
3302template <> struct DenseMapInfo<CatchHandlerType> {
3303 static CatchHandlerType getEmptyKey() {
3304 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3305 CatchHandlerType::ForDenseMap);
3306 }
3307
3308 static CatchHandlerType getTombstoneKey() {
3309 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3310 CatchHandlerType::ForDenseMap);
3311 }
3312
3313 static unsigned getHashValue(const CatchHandlerType &Base) {
3314 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3315 }
3316
3317 static bool isEqual(const CatchHandlerType &LHS,
3318 const CatchHandlerType &RHS) {
3319 return LHS == RHS;
3320 }
3321};
3322
3323// It's OK to treat CatchHandlerType as a POD type.
3324template <> struct isPodLike<CatchHandlerType> {
3325 static const bool value = true;
3326};
3327}
3328
3329namespace {
3330class CatchTypePublicBases {
3331 ASTContext &Ctx;
3332 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3333 const bool CheckAgainstPointer;
3334
3335 CXXCatchStmt *FoundHandler;
3336 CanQualType FoundHandlerType;
3337
3338public:
3339 CatchTypePublicBases(
3340 ASTContext &Ctx,
3341 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3342 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3343 FoundHandler(nullptr) {}
3344
3345 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3346 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3347
3348 static bool FindPublicBasesOfType(const CXXBaseSpecifier *S, CXXBasePath &,
3349 void *User) {
3350 auto &PBOT = *reinterpret_cast<CatchTypePublicBases *>(User);
3351 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3352 CatchHandlerType Check(S->getType(), PBOT.CheckAgainstPointer);
3353 auto M = PBOT.TypesToCheck;
3354 auto I = M.find(Check);
3355 if (I != M.end()) {
3356 PBOT.FoundHandler = I->second;
3357 PBOT.FoundHandlerType = PBOT.Ctx.getCanonicalType(S->getType());
3358 return true;
3359 }
3360 }
3361 return false;
3362 }
3363};
Dan Gohman28ade552010-07-26 21:25:24 +00003364}
3365
Sebastian Redl9b244a82008-12-22 21:35:02 +00003366/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3367/// handlers and creates a try statement from them.
Robert Wilhelmcafda822013-08-22 09:20:03 +00003368StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3369 ArrayRef<Stmt *> Handlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003370 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003371 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003372 !getSourceManager().isInSystemHeader(TryLoc))
Aaron Ballman8aee642902015-04-08 00:05:29 +00003373 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003374
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003375 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3376 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3377
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003378 sema::FunctionScopeInfo *FSI = getCurFunction();
3379
Reid Klecknere7175912015-02-02 22:15:31 +00003380 // C++ try is incompatible with SEH __try.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003381 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
Reid Klecknere7175912015-02-02 22:15:31 +00003382 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003383 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
Reid Klecknere7175912015-02-02 22:15:31 +00003384 }
3385
Robert Wilhelmcafda822013-08-22 09:20:03 +00003386 const unsigned NumHandlers = Handlers.size();
Aaron Ballman8aee642902015-04-08 00:05:29 +00003387 assert(!Handlers.empty() &&
Sebastian Redl9b244a82008-12-22 21:35:02 +00003388 "The parser shouldn't call this if there are no handlers.");
Sebastian Redl9b244a82008-12-22 21:35:02 +00003389
Aaron Ballman8aee642902015-04-08 00:05:29 +00003390 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003391 for (unsigned i = 0; i < NumHandlers; ++i) {
Aaron Ballman8aee642902015-04-08 00:05:29 +00003392 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003393
Aaron Ballman8aee642902015-04-08 00:05:29 +00003394 // Diagnose when the handler is a catch-all handler, but it isn't the last
3395 // handler for the try block. [except.handle]p5. Also, skip exception
3396 // declarations that are invalid, since we can't usefully report on them.
3397 if (!H->getExceptionDecl()) {
3398 if (i < NumHandlers - 1)
3399 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
Sebastian Redl63c4da02009-07-29 17:15:45 +00003400 continue;
Aaron Ballman8aee642902015-04-08 00:05:29 +00003401 } else if (H->getExceptionDecl()->isInvalidDecl())
3402 continue;
3403
3404 // Walk the type hierarchy to diagnose when this type has already been
3405 // handled (duplication), or cannot be handled (derivation inversion). We
3406 // ignore top-level cv-qualifiers, per [except.handle]p3
Aaron Ballmanaa301de2015-04-08 00:13:33 +00003407 CatchHandlerType HandlerCHT =
3408 (QualType)Context.getCanonicalType(H->getCaughtType());
Aaron Ballman8aee642902015-04-08 00:05:29 +00003409
3410 // We can ignore whether the type is a reference or a pointer; we need the
3411 // underlying declaration type in order to get at the underlying record
3412 // decl, if there is one.
3413 QualType Underlying = HandlerCHT.underlying();
3414 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3415 if (!RD->hasDefinition())
3416 continue;
3417 // Check that none of the public, unambiguous base classes are in the
3418 // map ([except.handle]p1). Give the base classes the same pointer
3419 // qualification as the original type we are basing off of. This allows
3420 // comparison against the handler type using the same top-level pointer
3421 // as the original type.
3422 CXXBasePaths Paths;
3423 Paths.setOrigin(RD);
3424 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3425 if (RD->lookupInBases(CatchTypePublicBases::FindPublicBasesOfType, &CTPB,
3426 Paths)) {
3427 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3428 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3429 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3430 diag::warn_exception_caught_by_earlier_handler)
3431 << H->getCaughtType();
3432 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3433 diag::note_previous_exception_handler)
3434 << Problem->getCaughtType();
3435 }
3436 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003437 }
Mike Stump11289f42009-09-09 15:08:12 +00003438
Aaron Ballman8aee642902015-04-08 00:05:29 +00003439 // Add the type the list of ones we have handled; diagnose if we've already
3440 // handled it.
3441 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3442 if (!R.second) {
3443 const CXXCatchStmt *Problem = R.first->second;
3444 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3445 diag::warn_exception_caught_by_earlier_handler)
3446 << H->getCaughtType();
3447 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3448 diag::note_previous_exception_handler)
3449 << Problem->getCaughtType();
Sebastian Redl63c4da02009-07-29 17:15:45 +00003450 }
3451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003453 FSI->setHasCXXTry(TryLoc);
John McCalla95172b2010-08-01 00:26:45 +00003454
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003455 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
Sebastian Redl9b244a82008-12-22 21:35:02 +00003456}
John Wiegley1c0675e2011-04-28 01:08:34 +00003457
Reid Klecknere7175912015-02-02 22:15:31 +00003458StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3459 Stmt *TryBlock, Stmt *Handler) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003460 assert(TryBlock && Handler);
3461
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003462 sema::FunctionScopeInfo *FSI = getCurFunction();
3463
Reid Klecknere7175912015-02-02 22:15:31 +00003464 // SEH __try is incompatible with C++ try. Borland appears to support this,
3465 // however.
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003466 if (!getLangOpts().Borland) {
3467 if (FSI->FirstCXXTryLoc.isValid()) {
3468 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3469 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3470 }
Reid Klecknere7175912015-02-02 22:15:31 +00003471 }
John Wiegley1c0675e2011-04-28 01:08:34 +00003472
Reid Klecknerdeeddec2015-02-05 18:56:03 +00003473 FSI->setHasSEHTry(TryLoc);
3474
3475 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3476 // track if they use SEH.
3477 DeclContext *DC = CurContext;
3478 while (DC && !DC->isFunctionOrMethod())
3479 DC = DC->getParent();
3480 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3481 if (FD)
3482 FD->setUsesSEHTry(true);
3483 else
3484 Diag(TryLoc, diag::err_seh_try_outside_functions);
Reid Klecknere7175912015-02-02 22:15:31 +00003485
3486 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
John Wiegley1c0675e2011-04-28 01:08:34 +00003487}
3488
3489StmtResult
3490Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3491 Expr *FilterExpr,
3492 Stmt *Block) {
3493 assert(FilterExpr && Block);
3494
3495 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003496 return StmtError(Diag(FilterExpr->getExprLoc(),
3497 diag::err_filter_expression_integral)
3498 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003499 }
3500
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003501 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003502}
3503
Nico Weberd64657f2015-03-09 02:47:59 +00003504void Sema::ActOnStartSEHFinallyBlock() {
3505 CurrentSEHFinally.push_back(CurScope);
3506}
3507
Nico Weberce903292015-03-09 03:17:15 +00003508void Sema::ActOnAbortSEHFinallyBlock() {
3509 CurrentSEHFinally.pop_back();
3510}
3511
Nico Weberd64657f2015-03-09 02:47:59 +00003512StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
John Wiegley1c0675e2011-04-28 01:08:34 +00003513 assert(Block);
Nico Weberd64657f2015-03-09 02:47:59 +00003514 CurrentSEHFinally.pop_back();
3515 return SEHFinallyStmt::Create(Context, Loc, Block);
John Wiegley1c0675e2011-04-28 01:08:34 +00003516}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003517
Nico Weberc7d05962014-07-06 22:32:59 +00003518StmtResult
3519Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
Nico Webereb61d4d2014-07-06 22:53:19 +00003520 Scope *SEHTryParent = CurScope;
3521 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3522 SEHTryParent = SEHTryParent->getParent();
3523 if (!SEHTryParent)
3524 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
Nico Weberd64657f2015-03-09 02:47:59 +00003525 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
Nico Webereb61d4d2014-07-06 22:53:19 +00003526
Nico Weber9b982072014-07-07 00:12:30 +00003527 return new (Context) SEHLeaveStmt(Loc);
Nico Weberc7d05962014-07-06 22:32:59 +00003528}
3529
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003530StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3531 bool IsIfExists,
3532 NestedNameSpecifierLoc QualifierLoc,
3533 DeclarationNameInfo NameInfo,
3534 Stmt *Nested)
3535{
3536 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003537 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003538 cast<CompoundStmt>(Nested));
3539}
3540
3541
Chad Rosier02a84392012-08-10 17:56:09 +00003542StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003543 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003544 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003545 UnqualifiedId &Name,
3546 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003547 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003548 SS.getWithLocInContext(Context),
3549 GetNameFromUnqualifiedId(Name),
3550 Nested);
3551}
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003552
3553RecordDecl*
Ben Langmuir37943a72013-05-03 19:00:33 +00003554Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3555 unsigned NumParams) {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003556 DeclContext *DC = CurContext;
3557 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3558 DC = DC->getParent();
3559
Craig Topperc3ec1492014-05-26 06:22:03 +00003560 RecordDecl *RD = nullptr;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003561 if (getLangOpts().CPlusPlus)
Craig Topperc3ec1492014-05-26 06:22:03 +00003562 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3563 /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003564 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003565 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003566
Alexey Bataev330de032014-10-29 12:21:55 +00003567 RD->setCapturedRecord();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003568 DC->addDecl(RD);
3569 RD->setImplicit();
3570 RD->startDefinition();
3571
Alexey Bataev9959db52014-05-06 10:08:46 +00003572 assert(NumParams > 0 && "CapturedStmt requires context parameter");
Ben Langmuir37943a72013-05-03 19:00:33 +00003573 CD = CapturedDecl::Create(Context, CurContext, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003574 DC->addDecl(CD);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003575 return RD;
3576}
3577
3578static void buildCapturedStmtCaptureList(
3579 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3580 SmallVectorImpl<Expr *> &CaptureInits,
3581 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3582
3583 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3584 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3585
3586 if (Cap->isThisCapture()) {
3587 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3588 CapturedStmt::VCK_This));
Richard Smithba71c082013-05-16 06:20:58 +00003589 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003590 continue;
Alexey Bataev330de032014-10-29 12:21:55 +00003591 } else if (Cap->isVLATypeCapture()) {
3592 Captures.push_back(
3593 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3594 CaptureInits.push_back(nullptr);
3595 continue;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003596 }
3597
3598 assert(Cap->isReferenceCapture() &&
3599 "non-reference capture not yet implemented");
3600
3601 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3602 CapturedStmt::VCK_ByRef,
3603 Cap->getVariable()));
Richard Smithba71c082013-05-16 06:20:58 +00003604 CaptureInits.push_back(Cap->getInitExpr());
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003605 }
3606}
3607
3608void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
Wei Pan17fbf6e2013-05-04 03:59:06 +00003609 CapturedRegionKind Kind,
3610 unsigned NumParams) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003611 CapturedDecl *CD = nullptr;
Ben Langmuir37943a72013-05-03 19:00:33 +00003612 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003613
Alexey Bataev9959db52014-05-06 10:08:46 +00003614 // Build the context parameter
3615 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3616 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3617 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3618 ImplicitParamDecl *Param
3619 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3620 DC->addDecl(Param);
3621
3622 CD->setContextParam(0, Param);
3623
3624 // Enter the capturing scope for this captured region.
3625 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3626
3627 if (CurScope)
3628 PushDeclContext(CurScope, CD);
3629 else
3630 CurContext = CD;
3631
3632 PushExpressionEvaluationContext(PotentiallyEvaluated);
3633}
3634
3635void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3636 CapturedRegionKind Kind,
3637 ArrayRef<CapturedParamNameType> Params) {
3638 CapturedDecl *CD = nullptr;
3639 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3640
3641 // Build the context parameter
3642 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3643 bool ContextIsFound = false;
3644 unsigned ParamNum = 0;
3645 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3646 E = Params.end();
3647 I != E; ++I, ++ParamNum) {
3648 if (I->second.isNull()) {
3649 assert(!ContextIsFound &&
3650 "null type has been found already for '__context' parameter");
3651 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3652 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3653 ImplicitParamDecl *Param
3654 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3655 DC->addDecl(Param);
3656 CD->setContextParam(ParamNum, Param);
3657 ContextIsFound = true;
3658 } else {
3659 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3660 ImplicitParamDecl *Param
3661 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3662 DC->addDecl(Param);
3663 CD->setParam(ParamNum, Param);
3664 }
3665 }
3666 assert(ContextIsFound && "no null type for '__context' parameter");
Alexey Bataev301a2d92014-05-14 10:40:54 +00003667 if (!ContextIsFound) {
3668 // Add __context implicitly if it is not specified.
3669 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3670 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3671 ImplicitParamDecl *Param =
3672 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3673 DC->addDecl(Param);
3674 CD->setContextParam(ParamNum, Param);
3675 }
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003676 // Enter the capturing scope for this captured region.
3677 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3678
3679 if (CurScope)
3680 PushDeclContext(CurScope, CD);
3681 else
3682 CurContext = CD;
3683
3684 PushExpressionEvaluationContext(PotentiallyEvaluated);
3685}
3686
Wei Pan17fbf6e2013-05-04 03:59:06 +00003687void Sema::ActOnCapturedRegionError() {
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003688 DiscardCleanupsInEvaluationContext();
3689 PopExpressionEvaluationContext();
3690
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003691 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3692 RecordDecl *Record = RSI->TheRecordDecl;
3693 Record->setInvalidDecl();
3694
Aaron Ballman62e47c42014-03-10 13:43:55 +00003695 SmallVector<Decl*, 4> Fields(Record->fields());
Alexey Bataev9959db52014-05-06 10:08:46 +00003696 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3697 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003698
Wei Pan17fbf6e2013-05-04 03:59:06 +00003699 PopDeclContext();
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003700 PopFunctionScopeInfo();
3701}
3702
3703StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3704 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3705
3706 SmallVector<CapturedStmt::Capture, 4> Captures;
3707 SmallVector<Expr *, 4> CaptureInits;
3708 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3709
3710 CapturedDecl *CD = RSI->TheCapturedDecl;
3711 RecordDecl *RD = RSI->TheRecordDecl;
3712
Wei Pan17fbf6e2013-05-04 03:59:06 +00003713 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3714 RSI->CapRegionKind, Captures,
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003715 CaptureInits, CD, RD);
3716
3717 CD->setBody(Res->getCapturedStmt());
3718 RD->completeDefinition();
3719
Wei Pan17fbf6e2013-05-04 03:59:06 +00003720 DiscardCleanupsInEvaluationContext();
3721 PopExpressionEvaluationContext();
3722
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003723 PopDeclContext();
3724 PopFunctionScopeInfo();
3725
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003726 return Res;
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003727}