blob: 66ddbaabf1c4d33123cde1de90c358f69c504f89 [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"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smith02e85f32011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall03318c12011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000033#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000034using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000035using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000036
John McCalldadc5752010-08-24 06:29:42 +000037StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000038 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000039 if (!E) // FIXME: FullExprArg has no error state?
40 return StmtError();
41
Chris Lattner903eb512008-07-25 23:18:17 +000042 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
43 // void expression for its side effects. Conversion to void allows any
44 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000045
Chris Lattner903eb512008-07-25 23:18:17 +000046 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000047 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000048}
49
50
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000051StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000052 bool HasLeadingEmptyMacro) {
53 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000054}
55
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000056StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
57 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000058 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattnercbafe8d2009-04-12 20:13:14 +000060 // If we have an invalid decl, just return an error.
61 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattner34a22092009-03-04 04:23:07 +000063 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000064}
Chris Lattneraf8d5812006-11-10 05:07:45 +000065
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000066void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
67 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000068
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000069 // If we have an invalid decl, just return.
70 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000071 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
72
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000073 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000074 var->setUsed();
75
John McCalld4631322011-06-17 06:42:21 +000076 // foreach variables are never actually initialized in the way that
77 // the parser came up with.
78 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000079
John McCalld4631322011-06-17 06:42:21 +000080 // In ARC, we don't need to retain the iteration variable of a fast
81 // enumeration loop. Rather than actually trying to catch that
82 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +000083 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +000084 QualType type = var->getType();
85
86 // Only do this if we inferred the lifetime. Inferred lifetime
87 // will show up as a local qualifier because explicit lifetime
88 // should have shown up as an AttributedType instead.
89 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
90 // Add 'const' and mark the variable as pseudo-strong.
91 var->setType(type.withConst());
92 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +000093 }
94 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000095}
96
Chandler Carruthe2669392011-08-17 09:34:37 +000097/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +000098///
99/// Adding a cast to void (or other expression wrappers) will prevent the
100/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000101static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000102 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000103 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000104
105 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
106 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthe2669392011-08-17 09:34:37 +0000107 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000108
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000109 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000110 IsNotEqual = Op->getOpcode() == BO_NE;
111 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000112 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
113 if (Op->getOperator() != OO_EqualEqual &&
114 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthe2669392011-08-17 09:34:37 +0000115 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000116
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000117 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000118 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
119 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120 } else {
121 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000122 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000123 }
124
125 // Suppress warnings when the operator, suspicious as it may be, comes from
126 // a macro expansion.
127 if (Loc.isMacroID())
Chandler Carruthe2669392011-08-17 09:34:37 +0000128 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000129
Chandler Carruthe2669392011-08-17 09:34:37 +0000130 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000131 << (unsigned)IsNotEqual << E->getSourceRange();
132
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000133 // If the LHS is a plausible entity to assign to, provide a fixit hint to
134 // correct common typos.
135 if (CanAssign) {
136 if (IsNotEqual)
137 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
138 << FixItHint::CreateReplacement(Loc, "|=");
139 else
140 S.Diag(Loc, diag::note_equality_comparison_to_assign)
141 << FixItHint::CreateReplacement(Loc, "=");
142 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000143
144 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000145}
146
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000147void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000148 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
149 return DiagnoseUnusedExprResult(Label->getSubStmt());
150
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000151 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000152 if (!E)
153 return;
154
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000155 SourceLocation Loc;
156 SourceRange R1, R2;
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +0000157 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
158 !E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000159 return;
Mike Stump11289f42009-09-09 15:08:12 +0000160
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000161 // Okay, we have an unused result. Depending on what the base expression is,
162 // we might want to make a more specific diagnostic. Check for one of these
163 // cases now.
164 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000165 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000166 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000167 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
168 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000169
Chandler Carruthe2669392011-08-17 09:34:37 +0000170 if (DiagnoseUnusedComparison(*this, E))
171 return;
172
John McCall34376a62010-12-04 03:47:34 +0000173 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000174 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000175 if (E->getType()->isVoidType())
176 return;
177
Chris Lattner1a6babf2009-10-13 04:53:48 +0000178 // If the callee has attribute pure, const, or warn_unused_result, warn with
179 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000180 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000181 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000182 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000183 return;
184 }
185 if (FD->getAttr<PureAttr>()) {
186 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
187 return;
188 }
189 if (FD->getAttr<ConstAttr>()) {
190 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
191 return;
192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193 }
John McCallb7bd14f2010-12-02 01:19:52 +0000194 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000195 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000196 Diag(Loc, diag::err_arc_unused_init_message) << R1;
197 return;
198 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000199 const ObjCMethodDecl *MD = ME->getMethodDecl();
200 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000201 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000202 return;
203 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000204 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
205 const Expr *Source = POE->getSyntacticForm();
206 if (isa<ObjCSubscriptRefExpr>(Source))
207 DiagID = diag::warn_unused_container_subscript_expr;
208 else
209 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000210 } else if (const CXXFunctionalCastExpr *FC
211 = dyn_cast<CXXFunctionalCastExpr>(E)) {
212 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
213 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
214 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000215 }
John McCall2351cb92010-04-06 22:24:14 +0000216 // Diagnose "(void*) blah" as a typo for "(void) blah".
217 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
218 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
219 QualType T = TI->getType();
220
221 // We really do want to use the non-canonical type here.
222 if (T == Context.VoidPtrTy) {
223 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
224
225 Diag(Loc, diag::warn_unused_voidptr)
226 << FixItHint::CreateRemoval(TL.getStarLoc());
227 return;
228 }
229 }
230
Ted Kremenek3427fac2011-02-23 01:52:04 +0000231 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000232}
233
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000234void Sema::ActOnStartOfCompoundStmt() {
235 PushCompoundScope();
236}
237
238void Sema::ActOnFinishOfCompoundStmt() {
239 PopCompoundScope();
240}
241
242sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
243 return getCurFunction()->CompoundScopes.back();
244}
245
John McCalldadc5752010-08-24 06:29:42 +0000246StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000247Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000248 MultiStmtArg elts, bool isStmtExpr) {
249 unsigned NumElts = elts.size();
250 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000251 // If we're in C89 mode, check that we don't have any decls after stmts. If
252 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000253 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000254 // Note that __extension__ can be around a decl.
255 unsigned i = 0;
256 // Skip over all declarations.
257 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
258 /*empty*/;
259
260 // We found the end of the list or a statement. Scan for another declstmt.
261 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
262 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattnerd864daf2007-08-27 04:29:41 +0000264 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000265 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000266 Diag(D->getLocation(), diag::ext_mixed_decls_code);
267 }
268 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000269 // Warn about unused expressions in statements.
270 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000271 // Ignore statements that are last in a statement expression.
272 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000273 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000275 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000276 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000277
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000278 // Check for suspicious empty body (null statement) in `for' and `while'
279 // statements. Don't do anything for template instantiations, this just adds
280 // noise.
281 if (NumElts != 0 && !CurrentInstantiationScope &&
282 getCurCompoundScope().HasEmptyLoopBodies) {
283 for (unsigned i = 0; i != NumElts - 1; ++i)
284 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
285 }
286
Ted Kremenek5a201952009-02-07 01:47:29 +0000287 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000288}
289
John McCalldadc5752010-08-24 06:29:42 +0000290StmtResult
John McCallb268a282010-08-23 23:25:46 +0000291Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
292 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000293 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000294 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000295
John McCallaab3e412010-08-25 08:40:02 +0000296 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000297 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000298 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000299 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000300
David Blaikiebbafb8a2012-03-11 07:00:24 +0000301 if (!getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000302 // C99 6.8.4.2p3: The expression shall be an integer constant.
303 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000304 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
305 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
306 if (!LHSVal)
307 return StmtError();
308 }
Richard Smithf8379a02012-01-18 23:55:52 +0000309
310 // GCC extension: The expression shall be an integer constant.
311
Richard Smithf4c51d92012-02-04 09:53:13 +0000312 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
313 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
314 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000315 }
316 }
317
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000318 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
319 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000320 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000321 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000322}
323
Chris Lattner34a22092009-03-04 04:23:07 +0000324/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000325void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000326 DiagnoseUnusedExprResult(SubStmt);
327
Chris Lattner34a22092009-03-04 04:23:07 +0000328 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000329 CS->setSubStmt(SubStmt);
330}
331
John McCalldadc5752010-08-24 06:29:42 +0000332StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000333Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000334 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000335 DiagnoseUnusedExprResult(SubStmt);
336
John McCallaab3e412010-08-25 08:40:02 +0000337 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000338 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000339 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000340 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000341
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000342 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000343 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000344 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000345}
346
John McCalldadc5752010-08-24 06:29:42 +0000347StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000348Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
349 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000350 // If the label was multiply defined, reject it now.
351 if (TheDecl->getStmt()) {
352 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
353 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000354 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000355 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000356
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000357 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000358 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
359 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000360 if (!TheDecl->isGnuLocal())
361 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000362 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000363}
364
Richard Smithc202b282012-04-14 00:33:13 +0000365StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
366 const AttrVec &Attrs,
367 Stmt *SubStmt) {
368 // Fill in the declaration and return it. Variable length will require to
369 // change this to AttributedStmt::Create(Context, ....);
370 // and probably using ArrayRef
371 AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt);
372 return Owned(LS);
373}
374
John McCalldadc5752010-08-24 06:29:42 +0000375StmtResult
John McCall48871652010-08-21 09:40:31 +0000376Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000377 Stmt *thenStmt, SourceLocation ElseLoc,
378 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000379 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000380
Douglas Gregor633caca2009-11-23 23:44:04 +0000381 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000382 if (CondVar) {
383 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000384 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000385 if (CondResult.isInvalid())
386 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000387 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000388 Expr *ConditionExpr = CondResult.takeAs<Expr>();
389 if (!ConditionExpr)
390 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000392 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000393
John McCallb268a282010-08-23 23:25:46 +0000394 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000395 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
396 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000397 }
398
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000399 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000400
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000402 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000403}
Steve Naroff86272ea2007-05-29 02:14:17 +0000404
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000405/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
406/// the specified width and sign. If an overflow occurs, detect it and emit
407/// the specified diagnostic.
408void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
409 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000410 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000411 unsigned DiagID) {
412 // Perform a conversion to the promoted condition type if needed.
413 if (NewWidth > Val.getBitWidth()) {
414 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000415 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000416 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000417
418 // If the input was signed and negative and the output is
419 // unsigned, don't bother to warn: this is implementation-defined
420 // behavior.
421 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000422 } else if (NewWidth < Val.getBitWidth()) {
423 // If this is a truncation, check for overflow.
424 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000425 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000426 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000427 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000428 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000429 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000430 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000431
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000432 // Regardless of whether a diagnostic was emitted, really do the
433 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000434 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000435 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000436 } else if (NewSign != Val.isSigned()) {
437 // Convert the sign to match the sign of the condition. This can cause
438 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000440 // behavior.
441 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000442 llvm::APSInt OldVal(Val);
443 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000444 }
445}
446
Chris Lattner67998452007-08-23 18:29:20 +0000447namespace {
448 struct CaseCompareFunctor {
449 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
450 const llvm::APSInt &RHS) {
451 return LHS.first < RHS;
452 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000453 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
454 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
455 return LHS.first < RHS.first;
456 }
Chris Lattner67998452007-08-23 18:29:20 +0000457 bool operator()(const llvm::APSInt &LHS,
458 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
459 return LHS < RHS.first;
460 }
461 };
462}
463
Chris Lattner4b2ff022007-09-21 18:15:22 +0000464/// CmpCaseVals - Comparison predicate for sorting case values.
465///
466static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
467 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
468 if (lhs.first < rhs.first)
469 return true;
470
471 if (lhs.first == rhs.first &&
472 lhs.second->getCaseLoc().getRawEncoding()
473 < rhs.second->getCaseLoc().getRawEncoding())
474 return true;
475 return false;
476}
477
Douglas Gregorbd6839732010-02-08 22:24:16 +0000478/// CmpEnumVals - Comparison predicate for sorting enumeration values.
479///
480static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
481 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
482{
483 return lhs.first < rhs.first;
484}
485
486/// EqEnumVals - Comparison preficate for uniqing enumeration values.
487///
488static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
489 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
490{
491 return lhs.first == rhs.first;
492}
493
Chris Lattnera96d4272009-10-16 16:45:22 +0000494/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
495/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000496static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
497 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
498 expr = cleanups->getSubExpr();
499 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
500 if (impcast->getCastKind() != CK_IntegralCast) break;
501 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000502 }
503 return expr->getType();
504}
505
John McCalldadc5752010-08-24 06:29:42 +0000506StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000508 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000509 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000510
Douglas Gregore60e41a2010-05-06 17:25:47 +0000511 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000512 if (CondVar) {
513 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000514 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
515 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000516 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000517
John McCallb268a282010-08-23 23:25:46 +0000518 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520
John McCallb268a282010-08-23 23:25:46 +0000521 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000522 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
John McCallb268a282010-08-23 23:25:46 +0000524 CondResult
Eli Friedman1da70392012-01-26 00:26:18 +0000525 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000526 PDiag(diag::err_typecheck_statement_requires_integer),
527 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000528 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000529 PDiag(diag::err_switch_explicit_conversion),
530 PDiag(diag::note_switch_conversion),
531 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000532 PDiag(diag::note_switch_conversion),
Richard Smith8dd34252012-02-04 07:07:42 +0000533 PDiag(0),
534 /*AllowScopedEnumerations*/ true);
John McCallb268a282010-08-23 23:25:46 +0000535 if (CondResult.isInvalid()) return StmtError();
536 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000537
John McCall5939b162011-08-06 07:30:58 +0000538 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
539 CondResult = UsualUnaryConversions(Cond);
540 if (CondResult.isInvalid()) return StmtError();
541 Cond = CondResult.take();
542
John McCall48871652010-08-21 09:40:31 +0000543 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000544 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000545 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000546 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000547 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000548 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000549 }
John McCalla95172b2010-08-01 00:26:45 +0000550
John McCallaab3e412010-08-25 08:40:02 +0000551 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
John McCallb268a282010-08-23 23:25:46 +0000553 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000554 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000555 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000556}
557
Gabor Greif16e02862010-10-01 22:05:14 +0000558static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
559 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000560 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000561 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000562 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000563 Val.setIsSigned(IsSigned);
564}
565
John McCalldadc5752010-08-24 06:29:42 +0000566StmtResult
John McCallb268a282010-08-23 23:25:46 +0000567Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
568 Stmt *BodyStmt) {
569 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000570 assert(SS == getCurFunction()->SwitchStack.back() &&
571 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000572
Steve Naroff42a350a2007-09-01 21:08:38 +0000573 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000574 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000575
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000576 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000577 if (!CondExpr) return StmtError();
578
579 QualType CondType = CondExpr->getType();
580
John McCalld3dfbd62010-05-18 03:19:21 +0000581 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000582 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000583 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000584
Chris Lattnera96d4272009-10-16 16:45:22 +0000585 // C++ 6.4.2.p2:
586 // Integral promotions are performed (on the switch condition).
587 //
588 // A case value unrepresentable by the original switch condition
589 // type (before the promotion) doesn't make sense, even when it can
590 // be represented by the promoted type. Therefore we need to find
591 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000592 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000593 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000595 // appropriate type now, just return an error.
596 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000597 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000598
Chris Lattner4ebae652010-04-16 23:34:13 +0000599 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000600 // switch(bool_expr) {...} is often a programmer error, e.g.
601 // switch(n && mask) { ... } // Doh - should be "n & mask".
602 // One can always use an if statement instead of switch(bool_expr).
603 Diag(SwitchLoc, diag::warn_bool_switch_condition)
604 << CondExpr->getSourceRange();
605 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000606 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000607
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000608 // Get the bitwidth of the switched-on value before promotions. We must
609 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000610 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000611 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000612 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000613 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000614 bool CondIsSigned
615 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000616
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000617 // Accumulate all of the case values in a vector so that we can sort them
618 // and detect duplicates. This vector contains the APInt for the case after
619 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000621 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000623 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000624 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
625 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000627 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000628
Chris Lattner10cb5e52007-08-23 06:23:56 +0000629 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000630
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000631 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000632 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000633
Anders Carlsson51873c22007-07-22 07:07:56 +0000634 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000635 if (TheDefaultStmt) {
636 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000637 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000638
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000639 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000640 // we'll return a valid AST. This requires recursing down the AST and
641 // finding it, not something we are set up to do right now. For now,
642 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000643 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000644 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000645 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000647 } else {
648 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattnera65e1f32008-01-16 19:17:22 +0000650 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000651
652 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
653 HasDependentValue = true;
654 break;
655 }
Mike Stump11289f42009-09-09 15:08:12 +0000656
Richard Smithf8379a02012-01-18 23:55:52 +0000657 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000658
David Blaikiebbafb8a2012-03-11 07:00:24 +0000659 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000660 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
661 // constant expression of the promoted type of the switch condition.
662 ExprResult ConvLo =
663 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
664 if (ConvLo.isInvalid()) {
665 CaseListIsErroneous = true;
666 continue;
667 }
668 Lo = ConvLo.take();
669 } else {
670 // We already verified that the expression has a i-c-e value (C99
671 // 6.8.4.2p3) - get that value now.
672 LoVal = Lo->EvaluateKnownConstInt(Context);
673
674 // If the LHS is not the same type as the condition, insert an implicit
675 // cast.
676 Lo = DefaultLvalueConversion(Lo).take();
677 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
678 }
679
680 // Convert the value to the same width/sign as the condition had prior to
681 // integral promotions.
682 //
683 // FIXME: This causes us to reject valid code:
684 // switch ((char)c) { case 256: case 0: return 0; }
685 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000686 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000687 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000688 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000689
Chris Lattnera65e1f32008-01-16 19:17:22 +0000690 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner10cb5e52007-08-23 06:23:56 +0000692 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000693 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000694 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000695 CS->getRHS()->isValueDependent()) {
696 HasDependentValue = true;
697 break;
698 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000699 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000700 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000701 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000702 }
703 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000704
705 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000706 // If we don't have a default statement, check whether the
707 // condition is constant.
708 llvm::APSInt ConstantCondValue;
709 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000710 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000711 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000712 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
713 Expr::SE_AllowSideEffects);
714 assert(!HasConstantCond ||
715 (ConstantCondValue.getBitWidth() == CondWidth &&
716 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000717 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000718 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000719
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000720 // Sort all the scalar case values so we can easily detect duplicates.
721 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
722
723 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000724 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
725 if (ShouldCheckConstantCond &&
726 CaseVals[i].first == ConstantCondValue)
727 ShouldCheckConstantCond = false;
728
729 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000730 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000731 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000732 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
733 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000734 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000735 // FIXME: We really want to remove the bogus case stmt from the
736 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000737 CaseListIsErroneous = true;
738 }
739 }
740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000742 // Detect duplicate case ranges, which usually don't exist at all in
743 // the first place.
744 if (!CaseRanges.empty()) {
745 // Sort all the case ranges by their low value so we can easily detect
746 // overlaps between ranges.
747 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000748
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000749 // Scan the ranges, computing the high values and removing empty ranges.
750 std::vector<llvm::APSInt> HiVals;
751 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000752 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000753 CaseStmt *CR = CaseRanges[i].second;
754 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000755 llvm::APSInt HiVal;
756
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000758 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
759 // constant expression of the promoted type of the switch condition.
760 ExprResult ConvHi =
761 CheckConvertedConstantExpression(Hi, CondType, HiVal,
762 CCEK_CaseValue);
763 if (ConvHi.isInvalid()) {
764 CaseListIsErroneous = true;
765 continue;
766 }
767 Hi = ConvHi.take();
768 } else {
769 HiVal = Hi->EvaluateKnownConstInt(Context);
770
771 // If the RHS is not the same type as the condition, insert an
772 // implicit cast.
773 Hi = DefaultLvalueConversion(Hi).take();
774 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000777 // Convert the value to the same width/sign as the condition.
778 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000779 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000780 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000782 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000784 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000785 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000786 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
787 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000788 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000789 CaseRanges.erase(CaseRanges.begin()+i);
790 --i, --e;
791 continue;
792 }
John McCalld3dfbd62010-05-18 03:19:21 +0000793
794 if (ShouldCheckConstantCond &&
795 LoVal <= ConstantCondValue &&
796 ConstantCondValue <= HiVal)
797 ShouldCheckConstantCond = false;
798
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000799 HiVals.push_back(HiVal);
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000802 // Rescan the ranges, looking for overlap with singleton values and other
803 // ranges. Since the range list is sorted, we only need to compare case
804 // ranges with their neighbors.
805 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
806 llvm::APSInt &CRLo = CaseRanges[i].first;
807 llvm::APSInt &CRHi = HiVals[i];
808 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000810 // Check to see whether the case range overlaps with any
811 // singleton cases.
812 CaseStmt *OverlapStmt = 0;
813 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000814
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000815 // Find the smallest value >= the lower bound. If I is in the
816 // case range, then we have overlap.
817 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
818 CaseVals.end(), CRLo,
819 CaseCompareFunctor());
820 if (I != CaseVals.end() && I->first < CRHi) {
821 OverlapVal = I->first; // Found overlap with scalar.
822 OverlapStmt = I->second;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000825 // Find the smallest value bigger than the upper bound.
826 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
827 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
828 OverlapVal = (I-1)->first; // Found overlap with scalar.
829 OverlapStmt = (I-1)->second;
830 }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000832 // Check to see if this case stmt overlaps with the subsequent
833 // case range.
834 if (i && CRLo <= HiVals[i-1]) {
835 OverlapVal = HiVals[i-1]; // Found overlap with range.
836 OverlapStmt = CaseRanges[i-1].second;
837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000839 if (OverlapStmt) {
840 // If we have a duplicate, report it.
841 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
842 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000843 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000844 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000845 // FIXME: We really want to remove the bogus case stmt from the
846 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000847 CaseListIsErroneous = true;
848 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000849 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000850 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000851
John McCalld3dfbd62010-05-18 03:19:21 +0000852 // Complain if we have a constant condition and we didn't find a match.
853 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
854 // TODO: it would be nice if we printed enums as enums, chars as
855 // chars, etc.
856 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
857 << ConstantCondValue.toString(10)
858 << CondExpr->getSourceRange();
859 }
860
861 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000862 // values. We only issue a warning if there is not 'default:', but
863 // we still do the analysis to preserve this information in the AST
864 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000865 //
Chris Lattner51679082010-09-16 17:09:42 +0000866 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000867
Douglas Gregorbd6839732010-02-08 22:24:16 +0000868 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000869 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000870 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000871 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000872 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000873 EnumValsTy EnumVals;
874
John McCalld3dfbd62010-05-18 03:19:21 +0000875 // Gather all enum values, set their type and sort them,
876 // allowing easier comparison with CaseVals.
877 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000878 EDI != ED->enumerator_end(); ++EDI) {
879 llvm::APSInt Val = EDI->getInitVal();
880 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie2d7c57e2012-04-30 02:36:29 +0000881 EnumVals.push_back(std::make_pair(Val, &*EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000882 }
883 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000884 EnumValsTy::iterator EIend =
885 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000886
887 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +0000888 EnumValsTy::const_iterator EI = EnumVals.begin();
889 for (CaseValsTy::const_iterator CI = CaseVals.begin();
890 CI != CaseVals.end(); CI++) {
891 while (EI != EIend && EI->first < CI->first)
892 EI++;
893 if (EI == EIend || EI->first > CI->first)
894 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000895 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +0000896 }
897 // See which of case ranges aren't in enum
898 EI = EnumVals.begin();
899 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
900 RI != CaseRanges.end() && EI != EIend; RI++) {
901 while (EI != EIend && EI->first < RI->first)
902 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000903
David Blaikiee476f972012-01-22 02:31:55 +0000904 if (EI == EIend || EI->first != RI->first) {
905 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000906 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +0000907 }
David Blaikiee476f972012-01-22 02:31:55 +0000908
909 llvm::APSInt Hi =
910 RI->second->getRHS()->EvaluateKnownConstInt(Context);
911 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
912 while (EI != EIend && EI->first < Hi)
913 EI++;
914 if (EI == EIend || EI->first != Hi)
915 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000916 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000918
Ted Kremenekc42f3452010-09-09 00:05:53 +0000919 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000920 CaseValsTy::const_iterator CI = CaseVals.begin();
921 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000922 bool hasCasesNotInSwitch = false;
923
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000925
David Blaikiee476f972012-01-22 02:31:55 +0000926 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000927 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000928 llvm::APSInt CIVal;
929 while (CI != CaseVals.end() && CI->first < EI->first)
930 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000931
Douglas Gregorbd6839732010-02-08 22:24:16 +0000932 if (CI != CaseVals.end() && CI->first == EI->first)
933 continue;
934
Ted Kremenekc42f3452010-09-09 00:05:53 +0000935 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000936 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +0000937 llvm::APSInt Hi =
938 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000939 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000940 if (EI->first <= Hi)
941 break;
942 }
943
Ted Kremenekc42f3452010-09-09 00:05:53 +0000944 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000945 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +0000946 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000947 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000949
David Blaikie60ac6382012-01-23 04:46:12 +0000950 if (TheDefaultStmt && UnhandledNames.empty())
951 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +0000952
Chris Lattner51679082010-09-16 17:09:42 +0000953 // Produce a nice diagnostic if multiple values aren't handled.
954 switch (UnhandledNames.size()) {
955 case 0: break;
956 case 1:
David Blaikie60ac6382012-01-23 04:46:12 +0000957 Diag(CondExpr->getExprLoc(), TheDefaultStmt
958 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +0000959 << UnhandledNames[0];
960 break;
961 case 2:
David Blaikie60ac6382012-01-23 04:46:12 +0000962 Diag(CondExpr->getExprLoc(), TheDefaultStmt
963 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +0000964 << UnhandledNames[0] << UnhandledNames[1];
965 break;
966 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +0000967 Diag(CondExpr->getExprLoc(), TheDefaultStmt
968 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +0000969 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
970 break;
971 default:
David Blaikie60ac6382012-01-23 04:46:12 +0000972 Diag(CondExpr->getExprLoc(), TheDefaultStmt
973 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +0000974 << (unsigned)UnhandledNames.size()
975 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
976 break;
977 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000978
979 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000980 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000981 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000982 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000983
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000984 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
985 diag::warn_empty_switch_body);
986
Mike Stump87c57ac2009-05-16 07:39:55 +0000987 // FIXME: If the case list was broken is some way, we don't have a good system
988 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000989 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000990 return StmtError();
991
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000992 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000993}
994
John McCalldadc5752010-08-24 06:29:42 +0000995StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000997 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000998 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
Douglas Gregor680f8612009-11-24 21:15:44 +00001000 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001001 if (CondVar) {
1002 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001003 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001004 if (CondResult.isInvalid())
1005 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001006 }
John McCallb268a282010-08-23 23:25:46 +00001007 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001008 if (!ConditionExpr)
1009 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
John McCallb268a282010-08-23 23:25:46 +00001011 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001013 if (isa<NullStmt>(Body))
1014 getCurCompoundScope().setHasEmptyLoopBodies();
1015
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001016 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001017 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001018}
1019
John McCalldadc5752010-08-24 06:29:42 +00001020StmtResult
John McCallb268a282010-08-23 23:25:46 +00001021Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001022 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001023 Expr *Cond, SourceLocation CondRParen) {
1024 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001025
John Wiegley01296292011-04-08 18:41:53 +00001026 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1027 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001028 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001029 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001030
John McCallacf0ee52010-10-08 02:01:28 +00001031 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001032 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001033 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001034 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001035 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
John McCallb268a282010-08-23 23:25:46 +00001037 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001038
John McCallb268a282010-08-23 23:25:46 +00001039 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001040}
1041
Richard Trieu451a5db2012-04-30 18:01:30 +00001042namespace {
1043 // This visitor will traverse a conditional statement and store all
1044 // the evaluated decls into a vector. Simple is set to true if none
1045 // of the excluded constructs are used.
1046 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1047 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1048 llvm::SmallVector<SourceRange, 10> &Ranges;
1049 bool Simple;
1050 PartialDiagnostic &PDiag;
1051public:
1052 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1053
1054 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1055 llvm::SmallVector<SourceRange, 10> &Ranges,
1056 PartialDiagnostic &PDiag) :
1057 Inherited(S.Context),
1058 Decls(Decls),
1059 Ranges(Ranges),
1060 Simple(true),
1061 PDiag(PDiag) {}
1062
1063 bool isSimple() { return Simple; }
1064
1065 // Replaces the method in EvaluatedExprVisitor.
1066 void VisitMemberExpr(MemberExpr* E) {
1067 Simple = false;
1068 }
1069
1070 // Any Stmt not whitelisted will cause the condition to be marked complex.
1071 void VisitStmt(Stmt *S) {
1072 Simple = false;
1073 }
1074
1075 void VisitBinaryOperator(BinaryOperator *E) {
1076 Visit(E->getLHS());
1077 Visit(E->getRHS());
1078 }
1079
1080 void VisitCastExpr(CastExpr *E) {
1081 Visit(E->getSubExpr());
1082 }
1083
1084 void VisitUnaryOperator(UnaryOperator *E) {
1085 // Skip checking conditionals with derefernces.
1086 if (E->getOpcode() == UO_Deref)
1087 Simple = false;
1088 else
1089 Visit(E->getSubExpr());
1090 }
1091
1092 void VisitConditionalOperator(ConditionalOperator *E) {
1093 Visit(E->getCond());
1094 Visit(E->getTrueExpr());
1095 Visit(E->getFalseExpr());
1096 }
1097
1098 void VisitParenExpr(ParenExpr *E) {
1099 Visit(E->getSubExpr());
1100 }
1101
1102 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1103 Visit(E->getOpaqueValue()->getSourceExpr());
1104 Visit(E->getFalseExpr());
1105 }
1106
1107 void VisitIntegerLiteral(IntegerLiteral *E) { }
1108 void VisitFloatingLiteral(FloatingLiteral *E) { }
1109 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1110 void VisitCharacterLiteral(CharacterLiteral *E) { }
1111 void VisitGNUNullExpr(GNUNullExpr *E) { }
1112 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1113
1114 void VisitDeclRefExpr(DeclRefExpr *E) {
1115 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1116 if (!VD) return;
1117
1118 Ranges.push_back(E->getSourceRange());
1119
1120 Decls.insert(VD);
1121 }
1122
1123 }; // end class DeclExtractor
1124
1125 // DeclMatcher checks to see if the decls are used in a non-evauluated
1126 // context.
1127 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1128 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1129 bool FoundDecl;
1130 //bool EvalDecl;
1131
1132public:
1133 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1134
1135 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1136 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1137 if (!Statement) return;
1138
1139 Visit(Statement);
1140 }
1141
1142 void VisitReturnStmt(ReturnStmt *S) {
1143 FoundDecl = true;
1144 }
1145
1146 void VisitBreakStmt(BreakStmt *S) {
1147 FoundDecl = true;
1148 }
1149
1150 void VisitGotoStmt(GotoStmt *S) {
1151 FoundDecl = true;
1152 }
1153
1154 void VisitCastExpr(CastExpr *E) {
1155 if (E->getCastKind() == CK_LValueToRValue)
1156 CheckLValueToRValueCast(E->getSubExpr());
1157 else
1158 Visit(E->getSubExpr());
1159 }
1160
1161 void CheckLValueToRValueCast(Expr *E) {
1162 E = E->IgnoreParenImpCasts();
1163
1164 if (isa<DeclRefExpr>(E)) {
1165 return;
1166 }
1167
1168 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1169 Visit(CO->getCond());
1170 CheckLValueToRValueCast(CO->getTrueExpr());
1171 CheckLValueToRValueCast(CO->getFalseExpr());
1172 return;
1173 }
1174
1175 if (BinaryConditionalOperator *BCO =
1176 dyn_cast<BinaryConditionalOperator>(E)) {
1177 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1178 CheckLValueToRValueCast(BCO->getFalseExpr());
1179 return;
1180 }
1181
1182 Visit(E);
1183 }
1184
1185 void VisitDeclRefExpr(DeclRefExpr *E) {
1186 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1187 if (Decls.count(VD))
1188 FoundDecl = true;
1189 }
1190
1191 bool FoundDeclInUse() { return FoundDecl; }
1192
1193 }; // end class DeclMatcher
1194
1195 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1196 Expr *Third, Stmt *Body) {
1197 // Condition is empty
1198 if (!Second) return;
1199
1200 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1201 Second->getLocStart())
1202 == DiagnosticsEngine::Ignored)
1203 return;
1204
1205 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1206 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1207 llvm::SmallVector<SourceRange, 10> Ranges;
1208 DeclExtractor DE(S, Decls, Ranges, PDiag);
1209 DE.Visit(Second);
1210
1211 // Don't analyze complex conditionals.
1212 if (!DE.isSimple()) return;
1213
1214 // No decls found.
1215 if (Decls.size() == 0) return;
1216
1217 // Don't warn on volatile decls.
1218 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1219 E = Decls.end();
1220 I != E; ++I)
1221 if ((*I)->getType().isVolatileQualified()) return;
1222
1223 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1224 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1225 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1226 return;
1227
1228 // Load decl names into diagnostic.
1229 if (Decls.size() > 4)
1230 PDiag << 0;
1231 else {
1232 PDiag << Decls.size();
1233 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1234 E = Decls.end();
1235 I != E; ++I)
1236 PDiag << (*I)->getDeclName();
1237 }
1238
1239 // Load SourceRanges into diagnostic if there is room.
1240 // Otherwise, load the SourceRange of the conditional expression.
1241 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1242 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1243 E = Ranges.end();
1244 I != E; ++I)
1245 PDiag << *I;
1246 else
1247 PDiag << Second->getSourceRange();
1248
1249 S.Diag(Ranges.begin()->getBegin(), PDiag);
1250 }
1251
1252} // end namespace
1253
John McCalldadc5752010-08-24 06:29:42 +00001254StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001255Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001256 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001257 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001258 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001259 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001260 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001261 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1262 // declare identifiers for objects having storage class 'auto' or
1263 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001264 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1265 DI!=DE; ++DI) {
1266 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001267 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001268 VD = 0;
1269 if (VD == 0)
1270 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1271 // FIXME: mark decl erroneous!
1272 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001273 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001274 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001275
Richard Trieu451a5db2012-04-30 18:01:30 +00001276 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1277
John McCalldadc5752010-08-24 06:29:42 +00001278 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001279 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001280 if (secondVar) {
1281 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001282 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001283 if (SecondResult.isInvalid())
1284 return StmtError();
1285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001286
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001287 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001288
Anders Carlsson1682af52009-08-01 01:39:59 +00001289 DiagnoseUnusedExprResult(First);
1290 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001291 DiagnoseUnusedExprResult(Body);
1292
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001293 if (isa<NullStmt>(Body))
1294 getCurCompoundScope().setHasEmptyLoopBodies();
1295
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296 return Owned(new (Context) ForStmt(Context, First,
1297 SecondResult.take(), ConditionVar,
1298 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001299 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001300}
1301
John McCall34376a62010-12-04 03:47:34 +00001302/// In an Objective C collection iteration statement:
1303/// for (x in y)
1304/// x can be an arbitrary l-value expression. Bind it up as a
1305/// full-expression.
1306StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001307 // Reduce placeholder expressions here. Note that this rejects the
1308 // use of pseudo-object l-values in this position.
1309 ExprResult result = CheckPlaceholderExpr(E);
1310 if (result.isInvalid()) return StmtError();
1311 E = result.take();
1312
John McCall34376a62010-12-04 03:47:34 +00001313 CheckImplicitConversions(E);
John McCallbc153352012-03-30 05:43:39 +00001314
1315 result = MaybeCreateExprWithCleanups(E);
1316 if (result.isInvalid()) return StmtError();
1317
1318 return Owned(static_cast<Stmt*>(result.take()));
John McCall34376a62010-12-04 03:47:34 +00001319}
1320
John McCall53848232011-07-27 01:07:15 +00001321ExprResult
1322Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1323 assert(collection);
1324
1325 // Bail out early if we've got a type-dependent expression.
1326 if (collection->isTypeDependent()) return Owned(collection);
1327
1328 // Perform normal l-value conversion.
1329 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1330 if (result.isInvalid())
1331 return ExprError();
1332 collection = result.take();
1333
1334 // The operand needs to have object-pointer type.
1335 // TODO: should we do a contextual conversion?
1336 const ObjCObjectPointerType *pointerType =
1337 collection->getType()->getAs<ObjCObjectPointerType>();
1338 if (!pointerType)
1339 return Diag(forLoc, diag::err_collection_expr_type)
1340 << collection->getType() << collection->getSourceRange();
1341
1342 // Check that the operand provides
1343 // - countByEnumeratingWithState:objects:count:
1344 const ObjCObjectType *objectType = pointerType->getObjectType();
1345 ObjCInterfaceDecl *iface = objectType->getInterface();
1346
1347 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001348 // Under ARC, it is an error not to have a forward-declared class.
1349 if (iface &&
1350 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001351 getLangOpts().ObjCAutoRefCount
Douglas Gregor4123a862011-11-14 22:10:01 +00001352 ? PDiag(diag::err_arc_collection_forward)
1353 << collection->getSourceRange()
1354 : PDiag(0))) {
John McCall53848232011-07-27 01:07:15 +00001355 // Otherwise, if we have any useful type information, check that
1356 // the type declares the appropriate method.
1357 } else if (iface || !objectType->qual_empty()) {
1358 IdentifierInfo *selectorIdents[] = {
1359 &Context.Idents.get("countByEnumeratingWithState"),
1360 &Context.Idents.get("objects"),
1361 &Context.Idents.get("count")
1362 };
1363 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1364
1365 ObjCMethodDecl *method = 0;
1366
1367 // If there's an interface, look in both the public and private APIs.
1368 if (iface) {
1369 method = iface->lookupInstanceMethod(selector);
1370 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1371 }
1372
1373 // Also check protocol qualifiers.
1374 if (!method)
1375 method = LookupMethodInQualifiedType(selector, pointerType,
1376 /*instance*/ true);
1377
1378 // If we didn't find it anywhere, give up.
1379 if (!method) {
1380 Diag(forLoc, diag::warn_collection_expr_type)
1381 << collection->getType() << selector << collection->getSourceRange();
1382 }
1383
1384 // TODO: check for an incompatible signature?
1385 }
1386
1387 // Wrap up any cleanups in the expression.
1388 return Owned(MaybeCreateExprWithCleanups(collection));
1389}
1390
John McCalldadc5752010-08-24 06:29:42 +00001391StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001392Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1393 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001394 Stmt *First, Expr *Second,
1395 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +00001396 if (First) {
1397 QualType FirstType;
1398 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001399 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001400 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1401 diag::err_toomany_element_decls));
1402
John McCall31168b02011-06-15 23:02:42 +00001403 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1404 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001405 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1406 // declare identifiers for objects having storage class 'auto' or
1407 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001408 if (!D->hasLocalStorage())
1409 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001410 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001411 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001412 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001413 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001414 return StmtError(Diag(First->getLocStart(),
1415 diag::err_selector_element_not_lvalue)
1416 << First->getSourceRange());
1417
Mike Stump11289f42009-09-09 15:08:12 +00001418 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001419 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001420 if (!FirstType->isDependentType() &&
1421 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001422 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001423 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001424 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001425 }
John McCall53848232011-07-27 01:07:15 +00001426
Ted Kremenek5a201952009-02-07 01:47:29 +00001427 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1428 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001429}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001430
Richard Smith02e85f32011-04-14 22:09:26 +00001431namespace {
1432
1433enum BeginEndFunction {
1434 BEF_begin,
1435 BEF_end
1436};
1437
1438/// Build a variable declaration for a for-range statement.
1439static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1440 QualType Type, const char *Name) {
1441 DeclContext *DC = SemaRef.CurContext;
1442 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1443 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1444 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1445 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001446 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001447 return Decl;
1448}
1449
1450/// Finish building a variable declaration for a for-range statement.
1451/// \return true if an error occurs.
1452static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1453 SourceLocation Loc, int diag) {
1454 // Deduce the type for the iterator variable now rather than leaving it to
1455 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1456 TypeSourceInfo *InitTSI = 0;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001457 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redl09edce02012-01-23 22:09:39 +00001458 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1459 Sema::DAR_Failed)
Richard Smith02e85f32011-04-14 22:09:26 +00001460 SemaRef.Diag(Loc, diag) << Init->getType();
1461 if (!InitTSI) {
1462 Decl->setInvalidDecl();
1463 return true;
1464 }
1465 Decl->setTypeSourceInfo(InitTSI);
1466 Decl->setType(InitTSI->getType());
1467
John McCall31168b02011-06-15 23:02:42 +00001468 // In ARC, infer lifetime.
1469 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1470 // we're doing the equivalent of fast iteration.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001471 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001472 SemaRef.inferObjCARCLifetime(Decl))
1473 Decl->setInvalidDecl();
1474
Richard Smith02e85f32011-04-14 22:09:26 +00001475 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1476 /*TypeMayContainAuto=*/false);
1477 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001478 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001479 return false;
1480}
1481
1482/// Produce a note indicating which begin/end function was implicitly called
1483/// by a C++0x for-range statement. This is often not obvious from the code,
1484/// nor from the diagnostics produced when analysing the implicit expressions
1485/// required in a for-range statement.
1486void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1487 BeginEndFunction BEF) {
1488 CallExpr *CE = dyn_cast<CallExpr>(E);
1489 if (!CE)
1490 return;
1491 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1492 if (!D)
1493 return;
1494 SourceLocation Loc = D->getLocation();
1495
1496 std::string Description;
1497 bool IsTemplate = false;
1498 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1499 Description = SemaRef.getTemplateArgumentBindingsText(
1500 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1501 IsTemplate = true;
1502 }
1503
1504 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1505 << BEF << IsTemplate << Description << E->getType();
1506}
1507
1508/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1509/// given LookupResult is non-empty, it is assumed to describe a member which
1510/// will be invoked. Otherwise, the function will be found via argument
1511/// dependent lookup.
1512static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1513 SourceLocation Loc,
1514 VarDecl *Decl,
1515 BeginEndFunction BEF,
1516 const DeclarationNameInfo &NameInfo,
1517 LookupResult &MemberLookup,
1518 Expr *Range) {
1519 ExprResult CallExpr;
1520 if (!MemberLookup.empty()) {
1521 ExprResult MemberRef =
1522 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1523 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001524 /*TemplateKWLoc=*/SourceLocation(),
1525 /*FirstQualifierInScope=*/0,
1526 MemberLookup,
Richard Smith02e85f32011-04-14 22:09:26 +00001527 /*TemplateArgs=*/0);
1528 if (MemberRef.isInvalid())
1529 return ExprError();
1530 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1531 Loc, 0);
1532 if (CallExpr.isInvalid())
1533 return ExprError();
1534 } else {
1535 UnresolvedSet<0> FoundNames;
1536 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1537 // std is an associated namespace.
1538 UnresolvedLookupExpr *Fn =
1539 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1540 NestedNameSpecifierLoc(), NameInfo,
1541 /*NeedsADL=*/true, /*Overloaded=*/false,
1542 FoundNames.begin(), FoundNames.end(),
1543 /*LookInStdNamespace=*/true);
1544 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00001545 0, /*AllowTypoCorrection=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001546 if (CallExpr.isInvalid()) {
1547 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1548 << Range->getType();
1549 return ExprError();
1550 }
1551 }
1552 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1553 diag::err_for_range_iter_deduction_failure)) {
1554 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1555 return ExprError();
1556 }
1557 return CallExpr;
1558}
1559
1560}
1561
1562/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1563///
1564/// C++0x [stmt.ranged]:
1565/// A range-based for statement is equivalent to
1566///
1567/// {
1568/// auto && __range = range-init;
1569/// for ( auto __begin = begin-expr,
1570/// __end = end-expr;
1571/// __begin != __end;
1572/// ++__begin ) {
1573/// for-range-declaration = *__begin;
1574/// statement
1575/// }
1576/// }
1577///
1578/// The body of the loop is not available yet, since it cannot be analysed until
1579/// we have determined the type of the for-range-declaration.
1580StmtResult
1581Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1582 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1583 SourceLocation RParenLoc) {
1584 if (!First || !Range)
1585 return StmtError();
1586
1587 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1588 assert(DS && "first part of for range not a decl stmt");
1589
1590 if (!DS->isSingleDecl()) {
1591 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1592 return StmtError();
1593 }
1594 if (DS->getSingleDecl()->isInvalidDecl())
1595 return StmtError();
1596
1597 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1598 return StmtError();
1599
1600 // Build auto && __range = range-init
1601 SourceLocation RangeLoc = Range->getLocStart();
1602 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1603 Context.getAutoRRefDeductType(),
1604 "__range");
1605 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1606 diag::err_for_range_deduction_failure))
1607 return StmtError();
1608
1609 // Claim the type doesn't contain auto: we've already done the checking.
1610 DeclGroupPtrTy RangeGroup =
1611 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1612 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1613 if (RangeDecl.isInvalid())
1614 return StmtError();
1615
1616 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1617 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1618 RParenLoc);
1619}
1620
1621/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1622StmtResult
1623Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1624 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1625 Expr *Inc, Stmt *LoopVarDecl,
1626 SourceLocation RParenLoc) {
1627 Scope *S = getCurScope();
1628
1629 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1630 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1631 QualType RangeVarType = RangeVar->getType();
1632
1633 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1634 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1635
1636 StmtResult BeginEndDecl = BeginEnd;
1637 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1638
1639 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1640 SourceLocation RangeLoc = RangeVar->getLocation();
1641
Ted Kremenekbed648e2011-10-10 22:36:28 +00001642 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1643
1644 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1645 VK_LValue, ColonLoc);
1646 if (BeginRangeRef.isInvalid())
1647 return StmtError();
1648
1649 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1650 VK_LValue, ColonLoc);
1651 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00001652 return StmtError();
1653
1654 QualType AutoType = Context.getAutoDeductType();
1655 Expr *Range = RangeVar->getInit();
1656 if (!Range)
1657 return StmtError();
1658 QualType RangeType = Range->getType();
1659
1660 if (RequireCompleteType(RangeLoc, RangeType,
1661 PDiag(diag::err_for_range_incomplete_type)))
1662 return StmtError();
1663
1664 // Build auto __begin = begin-expr, __end = end-expr.
1665 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1666 "__begin");
1667 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1668 "__end");
1669
1670 // Build begin-expr and end-expr and attach to __begin and __end variables.
1671 ExprResult BeginExpr, EndExpr;
1672 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1673 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1674 // __range + __bound, respectively, where __bound is the array bound. If
1675 // _RangeT is an array of unknown size or an array of incomplete type,
1676 // the program is ill-formed;
1677
1678 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001679 BeginExpr = BeginRangeRef;
1680 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001681 diag::err_for_range_iter_deduction_failure)) {
1682 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1683 return StmtError();
1684 }
1685
1686 // Find the array bound.
1687 ExprResult BoundExpr;
1688 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1689 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001690 Context.getPointerDiffType(),
1691 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001692 else if (const VariableArrayType *VAT =
1693 dyn_cast<VariableArrayType>(UnqAT))
1694 BoundExpr = VAT->getSizeExpr();
1695 else {
1696 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1697 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00001698 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00001699 }
1700
1701 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001702 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00001703 BoundExpr.get());
1704 if (EndExpr.isInvalid())
1705 return StmtError();
1706 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1707 diag::err_for_range_iter_deduction_failure)) {
1708 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1709 return StmtError();
1710 }
1711 } else {
1712 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1713 ColonLoc);
1714 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1715 ColonLoc);
1716
1717 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1718 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1719
1720 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1721 // - if _RangeT is a class type, the unqualified-ids begin and end are
1722 // looked up in the scope of class _RangeT as if by class member access
1723 // lookup (3.4.5), and if either (or both) finds at least one
1724 // declaration, begin-expr and end-expr are __range.begin() and
1725 // __range.end(), respectively;
1726 LookupQualifiedName(BeginMemberLookup, D);
1727 LookupQualifiedName(EndMemberLookup, D);
1728
1729 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1730 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1731 << RangeType << BeginMemberLookup.empty();
1732 return StmtError();
1733 }
1734 } else {
1735 // - otherwise, begin-expr and end-expr are begin(__range) and
1736 // end(__range), respectively, where begin and end are looked up with
1737 // argument-dependent lookup (3.4.2). For the purposes of this name
1738 // lookup, namespace std is an associated namespace.
1739 }
1740
1741 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1742 BEF_begin, BeginNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001743 BeginMemberLookup,
1744 BeginRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001745 if (BeginExpr.isInvalid())
1746 return StmtError();
1747
1748 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1749 BEF_end, EndNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001750 EndMemberLookup, EndRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001751 if (EndExpr.isInvalid())
1752 return StmtError();
1753 }
1754
1755 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1756 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1757 if (!Context.hasSameType(BeginType, EndType)) {
1758 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1759 << BeginType << EndType;
1760 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1761 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1762 }
1763
1764 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1765 // Claim the type doesn't contain auto: we've already done the checking.
1766 DeclGroupPtrTy BeginEndGroup =
1767 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1768 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1769
Ted Kremenekbed648e2011-10-10 22:36:28 +00001770 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1771 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00001772 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001773 if (BeginRef.isInvalid())
1774 return StmtError();
1775
Richard Smith02e85f32011-04-14 22:09:26 +00001776 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1777 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001778 if (EndRef.isInvalid())
1779 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00001780
1781 // Build and check __begin != __end expression.
1782 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1783 BeginRef.get(), EndRef.get());
1784 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1785 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1786 if (NotEqExpr.isInvalid()) {
1787 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1788 if (!Context.hasSameType(BeginType, EndType))
1789 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1790 return StmtError();
1791 }
1792
1793 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001794 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1795 VK_LValue, ColonLoc);
1796 if (BeginRef.isInvalid())
1797 return StmtError();
1798
Richard Smith02e85f32011-04-14 22:09:26 +00001799 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1800 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1801 if (IncrExpr.isInvalid()) {
1802 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1803 return StmtError();
1804 }
1805
1806 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001807 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1808 VK_LValue, ColonLoc);
1809 if (BeginRef.isInvalid())
1810 return StmtError();
1811
Richard Smith02e85f32011-04-14 22:09:26 +00001812 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1813 if (DerefExpr.isInvalid()) {
1814 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1815 return StmtError();
1816 }
1817
1818 // Attach *__begin as initializer for VD.
1819 if (!LoopVar->isInvalidDecl()) {
1820 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1821 /*TypeMayContainAuto=*/true);
1822 if (LoopVar->isInvalidDecl())
1823 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1824 }
Richard Smithf9603352011-06-21 23:07:19 +00001825 } else {
1826 // The range is implicitly used as a placeholder when it is dependent.
1827 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001828 }
1829
1830 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1831 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1832 NotEqExpr.take(), IncrExpr.take(),
1833 LoopVarDS, /*Body=*/0, ForLoc,
1834 ColonLoc, RParenLoc));
1835}
1836
1837/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1838/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1839/// body cannot be performed until after the type of the range variable is
1840/// determined.
1841StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1842 if (!S || !B)
1843 return StmtError();
1844
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001845 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1846 ForStmt->setBody(B);
1847
1848 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1849 diag::warn_empty_range_based_for_body);
1850
Richard Smith02e85f32011-04-14 22:09:26 +00001851 return S;
1852}
1853
Chris Lattnercab02a62011-02-17 20:34:02 +00001854StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1855 SourceLocation LabelLoc,
1856 LabelDecl *TheDecl) {
1857 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001858 TheDecl->setUsed();
1859 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001860}
Chris Lattner1c310502007-05-31 06:00:00 +00001861
John McCalldadc5752010-08-24 06:29:42 +00001862StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001863Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001864 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001865 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001866 if (!E->isTypeDependent()) {
1867 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001868 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001869 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001870 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001871 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1872 if (ExprRes.isInvalid())
1873 return StmtError();
1874 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001875 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001876 return StmtError();
Eli Friedman9ccdb1d2012-01-31 22:47:07 +00001877 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001878 }
John McCalla95172b2010-08-01 00:26:45 +00001879
John McCallaab3e412010-08-25 08:40:02 +00001880 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001881
Douglas Gregor30776d42009-05-16 00:20:29 +00001882 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001883}
1884
John McCalldadc5752010-08-24 06:29:42 +00001885StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001886Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001887 Scope *S = CurScope->getContinueParent();
1888 if (!S) {
1889 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001890 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001891 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001892
Ted Kremenek5a201952009-02-07 01:47:29 +00001893 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001894}
1895
John McCalldadc5752010-08-24 06:29:42 +00001896StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001897Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001898 Scope *S = CurScope->getBreakParent();
1899 if (!S) {
1900 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001901 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001902 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001903
Ted Kremenek5a201952009-02-07 01:47:29 +00001904 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001905}
1906
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001908/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001909///
Douglas Gregor5d369002011-01-21 18:05:27 +00001910/// \param ReturnType If we're determining the copy elision candidate for
1911/// a return statement, this is the return type of the function. If we're
1912/// determining the copy elision candidate for a throw expression, this will
1913/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001914///
Douglas Gregor5d369002011-01-21 18:05:27 +00001915/// \param E The expression being returned from the function or block, or
1916/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001917///
Douglas Gregor86394412011-05-20 15:00:53 +00001918/// \param AllowFunctionParameter Whether we allow function parameters to
1919/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1920/// we re-use this logic to determine whether we should try to move as part of
1921/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001922///
1923/// \returns The NRVO candidate variable, if the return statement may use the
1924/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001925const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1926 Expr *E,
1927 bool AllowFunctionParameter) {
1928 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001929 // - in a return statement in a function with ...
1930 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001931 if (!ReturnType.isNull()) {
1932 if (!ReturnType->isRecordType())
1933 return 0;
1934 // ... the same cv-unqualified type as the function return type ...
1935 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1936 return 0;
1937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
1939 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001940 // (other than a function or catch-clause parameter)) ...
1941 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001942 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001943 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001944 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1945 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001946 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
John McCall03318c12011-11-11 03:57:31 +00001948 // ...object (other than a function or catch-clause parameter)...
1949 if (VD->getKind() != Decl::Var &&
1950 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
1951 return 0;
1952 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
John McCall03318c12011-11-11 03:57:31 +00001954 // ...automatic...
1955 if (!VD->hasLocalStorage()) return 0;
1956
1957 // ...non-volatile...
1958 if (VD->getType().isVolatileQualified()) return 0;
1959 if (VD->getType()->isReferenceType()) return 0;
1960
1961 // __block variables can't be allocated in a way that permits NRVO.
1962 if (VD->hasAttr<BlocksAttr>()) return 0;
1963
1964 // Variables with higher required alignment than their type's ABI
1965 // alignment cannot use NRVO.
1966 if (VD->hasAttr<AlignedAttr>() &&
1967 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
1968 return 0;
1969
1970 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001971}
1972
Douglas Gregor626fbed2011-01-21 21:08:57 +00001973/// \brief Perform the initialization of a potentially-movable value, which
1974/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001975///
1976/// This routine implements C++0x [class.copy]p33, which attempts to treat
1977/// returned lvalues as rvalues in certain cases (to prefer move construction),
1978/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001980Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1981 const VarDecl *NRVOCandidate,
1982 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001983 Expr *Value,
1984 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001985 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986 // When the criteria for elision of a copy operation are met or would
1987 // be met save for the fact that the source object is a function
1988 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001989 // overload resolution to select the constructor for the copy is first
1990 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001991 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001992 if (AllowNRVO &&
1993 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001995 Value->getType(), CK_LValueToRValue,
1996 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997
Douglas Gregorf282a762011-01-21 19:38:21 +00001998 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002000 = InitializationKind::CreateCopy(Value->getLocStart(),
2001 Value->getLocStart());
2002 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
2004 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002005 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002006 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002007 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002008 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002009 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2010 StepEnd = Seq.step_end();
2011 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002012 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002013 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014
2015 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002016 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002017
Douglas Gregorf282a762011-01-21 19:38:21 +00002018 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002019 = Constructor->getParamDecl(0)->getType()
2020 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021
Douglas Gregorf282a762011-01-21 19:38:21 +00002022 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002023 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002024 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2025 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002026 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027
Douglas Gregorf282a762011-01-21 19:38:21 +00002028 // Promote "AsRvalue" to the heap, since we now need this
2029 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002030 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002032 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033
Douglas Gregorf282a762011-01-21 19:38:21 +00002034 // Complete type-checking the initialization of the return type
2035 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002036 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00002037 }
2038 }
2039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
Douglas Gregorf282a762011-01-21 19:38:21 +00002041 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002043 // (again) now with the return value expression as written.
2044 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002045 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Douglas Gregorf282a762011-01-21 19:38:21 +00002047 return Res;
2048}
2049
Eli Friedman34b49062012-01-26 03:00:14 +00002050/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2051/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002052///
John McCalldadc5752010-08-24 06:29:42 +00002053StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002054Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2055 // If this is the first return we've seen, infer the return type.
2056 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2057 // rules which allows multiple return statements.
2058 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2059 if (CurCap->HasImplicitReturnType) {
2060 QualType ReturnT;
Douglas Gregor940a5502012-02-09 18:40:39 +00002061 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002062 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2063 if (Result.isInvalid())
2064 return StmtError();
2065 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002066
Eli Friedman34b49062012-01-26 03:00:14 +00002067 if (!RetValExp->isTypeDependent())
2068 ReturnT = RetValExp->getType();
2069 else
2070 ReturnT = Context.DependentTy;
Douglas Gregor940a5502012-02-09 18:40:39 +00002071 } else {
2072 if (RetValExp) {
2073 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2074 // initializer list, because it is not an expression (even
2075 // though we represent it as one). We still deduce 'void'.
2076 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2077 << RetValExp->getSourceRange();
2078 }
2079
Eli Friedman34b49062012-01-26 03:00:14 +00002080 ReturnT = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002081 }
Eli Friedman34b49062012-01-26 03:00:14 +00002082 // We require the return types to strictly match here.
2083 if (!CurCap->ReturnType.isNull() &&
2084 !CurCap->ReturnType->isDependentType() &&
2085 !ReturnT->isDependentType() &&
2086 !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002087 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
Douglas Gregorb9e38f12012-02-15 15:57:22 +00002088 << ReturnT << CurCap->ReturnType
Douglas Gregor85dae8922012-02-15 15:59:09 +00002089 << (getCurLambda() != 0);
Eli Friedman34b49062012-01-26 03:00:14 +00002090 return StmtError();
2091 }
2092 CurCap->ReturnType = ReturnT;
Steve Naroffc540d662008-09-03 18:15:37 +00002093 }
Eli Friedman34b49062012-01-26 03:00:14 +00002094 QualType FnRetType = CurCap->ReturnType;
2095 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002096
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002097 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002098 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2099 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2100 return StmtError();
2101 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002102 } else {
2103 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2104 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2105 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2106 return StmtError();
2107 }
2108 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002109
Steve Naroffc540d662008-09-03 18:15:37 +00002110 // Otherwise, verify that this result type matches the previous one. We are
2111 // pickier with blocks than for normal functions because we don't have GCC
2112 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002113 const VarDecl *NRVOCandidate = 0;
John McCall5500ef22011-08-17 22:09:46 +00002114 if (FnRetType->isDependentType()) {
2115 // Delay processing for now. TODO: there are lots of dependent
2116 // types we can conclusively prove aren't void.
2117 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002118 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002119 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002120 (RetValExp->isTypeDependent() ||
2121 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002122 if (!getLangOpts().CPlusPlus &&
2123 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002124 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002125 else {
2126 Diag(ReturnLoc, diag::err_return_block_has_expr);
2127 RetValExp = 0;
2128 }
Steve Naroffc540d662008-09-03 18:15:37 +00002129 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002130 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002131 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2132 } else if (!RetValExp->isTypeDependent()) {
2133 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002134
John McCall5500ef22011-08-17 22:09:46 +00002135 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2136 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2137 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002138
John McCall5500ef22011-08-17 22:09:46 +00002139 // In C++ the return statement is handled via a copy initialization.
2140 // the C version of which boils down to CheckSingleAssignmentConstraints.
2141 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2142 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2143 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002144 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002145 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2146 FnRetType, RetValExp);
2147 if (Res.isInvalid()) {
2148 // FIXME: Cleanup temporaries here, anyway?
2149 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002150 }
John McCall5500ef22011-08-17 22:09:46 +00002151 RetValExp = Res.take();
2152 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002153 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002154
John McCall75f92b52011-08-17 21:34:14 +00002155 if (RetValExp) {
2156 CheckImplicitConversions(RetValExp, ReturnLoc);
2157 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2158 }
John McCall5500ef22011-08-17 22:09:46 +00002159 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2160 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002161
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002163 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002164 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002165 !CurContext->isDependentContext())
2166 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002168 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002169}
Chris Lattneraf8d5812006-11-10 05:07:45 +00002170
John McCalldadc5752010-08-24 06:29:42 +00002171StmtResult
John McCallb268a282010-08-23 23:25:46 +00002172Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002173 // Check for unexpanded parameter packs.
2174 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2175 return StmtError();
2176
Eli Friedman34b49062012-01-26 03:00:14 +00002177 if (isa<CapturingScopeInfo>(getCurFunction()))
2178 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00002179
Chris Lattner79413952008-12-04 23:50:19 +00002180 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002181 QualType RelatedRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002182 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00002183 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00002184 if (FD->hasAttr<NoReturnAttr>() ||
2185 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00002186 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002187 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002188 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman410fc7a2012-03-30 01:13:43 +00002189 FnRetType = MD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00002190 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2191 // In the implementation of a method with a related return type, the
2192 // type used to type-check the validity of return statements within the
2193 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002194 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2195 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002196 }
2197 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002198 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002199
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002200 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002201 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002202 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002203 if (isa<InitListExpr>(RetValExp)) {
2204 // We simply never allow init lists as the return value of void
2205 // functions. This is compatible because this was never allowed before,
2206 // so there's no legacy code to deal with.
2207 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2208 int FunctionKind = 0;
2209 if (isa<ObjCMethodDecl>(CurDecl))
2210 FunctionKind = 1;
2211 else if (isa<CXXConstructorDecl>(CurDecl))
2212 FunctionKind = 2;
2213 else if (isa<CXXDestructorDecl>(CurDecl))
2214 FunctionKind = 3;
2215
2216 Diag(ReturnLoc, diag::err_return_init_list)
2217 << CurDecl->getDeclName() << FunctionKind
2218 << RetValExp->getSourceRange();
2219
2220 // Drop the expression.
2221 RetValExp = 0;
2222 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002223 // C99 6.8.6.4p1 (ext_ since GCC warns)
2224 unsigned D = diag::ext_return_has_expr;
2225 if (RetValExp->getType()->isVoidType())
2226 D = diag::ext_return_has_void_expr;
2227 else {
2228 ExprResult Result = Owned(RetValExp);
2229 Result = IgnoredValueConversions(Result.take());
2230 if (Result.isInvalid())
2231 return StmtError();
2232 RetValExp = Result.take();
2233 RetValExp = ImpCastExprToType(RetValExp,
2234 Context.VoidTy, CK_ToVoid).take();
2235 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002236
Nick Lewycky1be750a2011-06-01 07:44:31 +00002237 // return (some void expression); is legal in C++.
2238 if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002239 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002240 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002241
2242 int FunctionKind = 0;
2243 if (isa<ObjCMethodDecl>(CurDecl))
2244 FunctionKind = 1;
2245 else if (isa<CXXConstructorDecl>(CurDecl))
2246 FunctionKind = 2;
2247 else if (isa<CXXDestructorDecl>(CurDecl))
2248 FunctionKind = 3;
2249
Nick Lewycky1be750a2011-06-01 07:44:31 +00002250 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002251 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002252 << RetValExp->getSourceRange();
2253 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002254 }
Mike Stump11289f42009-09-09 15:08:12 +00002255
Sebastian Redleef474c2012-02-22 10:50:08 +00002256 if (RetValExp) {
2257 CheckImplicitConversions(RetValExp, ReturnLoc);
2258 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2259 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002260 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002261
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002262 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2263 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002264 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2265 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002266 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002267
2268 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002269 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002270 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002271 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002272 Result = new (Context) ReturnStmt(ReturnLoc);
2273 } else {
2274 const VarDecl *NRVOCandidate = 0;
2275 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2276 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002277
Eli Friedman410fc7a2012-03-30 01:13:43 +00002278 if (!RelatedRetType.isNull()) {
2279 // If we have a related result type, perform an extra conversion here.
2280 // FIXME: The diagnostics here don't really describe what is happening.
2281 InitializedEntity Entity =
2282 InitializedEntity::InitializeTemporary(RelatedRetType);
2283
2284 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2285 RetValExp);
2286 if (Res.isInvalid()) {
2287 // FIXME: Cleanup temporaries here, anyway?
2288 return StmtError();
2289 }
2290 RetValExp = Res.takeAs<Expr>();
2291 }
2292
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002293 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2294 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2295 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002296
John McCallfa272342011-06-16 23:24:51 +00002297 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002298 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002299 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002300 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002301 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002302 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002304 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002305 if (Res.isInvalid()) {
2306 // FIXME: Cleanup temporaries here, anyway?
2307 return StmtError();
2308 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002309
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002310 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002312 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002314
John McCallacf0ee52010-10-08 02:01:28 +00002315 if (RetValExp) {
2316 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00002317 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00002318 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002319 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321
2322 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002323 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002324 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002325 !CurContext->isDependentContext())
2326 FunctionScopes.back()->Returns.push_back(Result);
John McCall31168b02011-06-15 23:02:42 +00002327
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002328 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002329}
2330
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002331/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2332/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2333/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2334/// provide a strong guidance to not use it.
2335///
2336/// This method checks to see if the argument is an acceptable l-value and
2337/// returns false if it is a case we can handle.
2338static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00002339 // Type dependent expressions will be checked during instantiation.
2340 if (E->isTypeDependent())
2341 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002342
John McCall086a4642010-11-24 05:12:34 +00002343 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002344 return false; // Cool, this is an lvalue.
2345
2346 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2347 // are supposed to allow.
2348 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00002349 if (E != E2 && E2->isLValue()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (!S.getLangOpts().HeinousExtensions)
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002351 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2352 << E->getSourceRange();
2353 else
2354 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2355 << E->getSourceRange();
2356 // Accept, even if we emitted an error diagnostic.
2357 return false;
2358 }
2359
2360 // None of the above, just randomly invalid non-lvalue.
2361 return true;
2362}
2363
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002364/// isOperandMentioned - Return true if the specified operand # is mentioned
2365/// anywhere in the decomposed asm string.
2366static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00002367 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002368 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2369 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2370 if (!Piece.isOperand()) continue;
2371
2372 // If this is a reference to the input and if the input was the smaller
2373 // one, then we have to reject this asm.
2374 if (Piece.getOperandNo() == OpNo)
2375 return true;
2376 }
2377
2378 return false;
2379}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002380
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002381StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2382 bool IsVolatile, unsigned NumOutputs,
2383 unsigned NumInputs, IdentifierInfo **Names,
2384 MultiExprArg constraints, MultiExprArg exprs,
2385 Expr *asmString, MultiExprArg clobbers,
2386 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002387 unsigned NumClobbers = clobbers.size();
2388 StringLiteral **Constraints =
2389 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00002390 Expr **Exprs = exprs.get();
2391 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00002392 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2393
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002394 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattner496acc12008-08-18 19:55:17 +00002396 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002397 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002398 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2399 << AsmString->getSourceRange());
2400
Chris Lattner496acc12008-08-18 19:55:17 +00002401 for (unsigned i = 0; i != NumOutputs; i++) {
2402 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002403 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002404 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2405 << Literal->getSourceRange());
2406
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002407 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002408 if (Names[i])
2409 OutputName = Names[i]->getName();
2410
2411 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002412 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002413 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002414 diag::err_asm_invalid_output_constraint)
2415 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002416
Anders Carlssonf511f642007-11-27 04:11:28 +00002417 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002418 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002419 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002420 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002421 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002422 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002423 }
Mike Stump11289f42009-09-09 15:08:12 +00002424
Chris Lattnerd9725f72009-04-26 07:16:29 +00002425 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002426 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002427
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002428 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002429
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002430 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002431 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002432 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002433 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2434 << Literal->getSourceRange());
2435
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002436 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002437 if (Names[i])
2438 InputName = Names[i]->getName();
2439
2440 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002441 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002442 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002443 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002444 diag::err_asm_invalid_input_constraint)
2445 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002446 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002447
Eli Friedman47e78572009-05-03 07:49:42 +00002448 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002449
Anders Carlsson224fca82009-01-20 20:49:22 +00002450 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002451 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002452 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002453 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002454 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002455 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002456 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002457 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002458
Chris Lattnerd9725f72009-04-26 07:16:29 +00002459 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002460 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002461 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002462 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002463 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002464 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002465 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
John Wiegley01296292011-04-08 18:41:53 +00002468 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2469 if (Result.isInvalid())
2470 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002471
John Wiegley01296292011-04-08 18:41:53 +00002472 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002473 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002474 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002475
Anders Carlsson290aa852007-11-25 00:25:21 +00002476 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002477 for (unsigned i = 0; i != NumClobbers; i++) {
2478 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002479 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002480 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2481 << Literal->getSourceRange());
2482
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002483 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002484
Douglas Gregore8bbc122011-09-02 00:18:52 +00002485 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002486 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002487 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002488 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002489
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002490 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2492 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002493 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002494 // Validate the asm string, ensuring it makes sense given the operands we
2495 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002496 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002497 unsigned DiagOffs;
2498 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002499 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2500 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002501 return StmtError();
2502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
Chris Lattner34b51e82009-05-03 05:55:43 +00002504 // Validate tied input operands for type mismatches.
2505 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2506 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattner34b51e82009-05-03 05:55:43 +00002508 // If this is a tied constraint, verify that the output and input have
2509 // either exactly the same type, or that they are int/ptr operands with the
2510 // same size (int/long, int*/long, are ok etc).
2511 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002512
Chris Lattner34b51e82009-05-03 05:55:43 +00002513 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002514 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002515 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002516 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedman8eac6c22011-09-14 19:20:00 +00002517
2518 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2519 continue;
2520
Chris Lattner2c295cf2009-05-03 05:59:17 +00002521 QualType InTy = InputExpr->getType();
2522 QualType OutTy = OutputExpr->getType();
2523 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002524 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002525
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002526 // Decide if the input and output are in the same domain (integer/ptr or
2527 // floating point.
2528 enum AsmDomain {
2529 AD_Int, AD_FP, AD_Other
2530 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002531
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002532 if (InTy->isIntegerType() || InTy->isPointerType())
2533 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002534 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002535 InputDomain = AD_FP;
2536 else
2537 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002539 if (OutTy->isIntegerType() || OutTy->isPointerType())
2540 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002541 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002542 OutputDomain = AD_FP;
2543 else
2544 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002545
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002546 // They are ok if they are the same size and in the same domain. This
2547 // allows tying things like:
2548 // void* to int*
2549 // void* to int if they are the same size.
2550 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002552 uint64_t OutSize = Context.getTypeSize(OutTy);
2553 uint64_t InSize = Context.getTypeSize(InTy);
2554 if (OutSize == InSize && InputDomain == OutputDomain &&
2555 InputDomain != AD_Other)
2556 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002558 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002559 // then we can promote the smaller one to a larger input and the asm string
2560 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002561 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002562
2563 // If this is a reference to the input and if the input was the smaller
2564 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002565 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002566 // This is a use in the asm string of the smaller operand. Since we
2567 // codegen this by promoting to a wider value, the asm will get printed
2568 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002569 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002570 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002571 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002572 // If this is a reference to the output, and if the output is the larger
2573 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002574 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002575 }
Mike Stump11289f42009-09-09 15:08:12 +00002576
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002577 // If the smaller value wasn't mentioned in the asm string, and if the
2578 // output was a register, just extend the shorter one to the size of the
2579 // larger one.
2580 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2581 OutputConstraintInfos[TiedTo].allowsRegister())
2582 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002583
Chris Lattner93ede022011-02-21 22:09:29 +00002584 // Either both of the operands were mentioned or the smaller one was
2585 // mentioned. One more special case that we'll allow: if the tied input is
2586 // integer, unmentioned, and is a constant, then we'll allow truncating it
2587 // down to the size of the destination.
2588 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2589 !isOperandMentioned(InputOpNo, Pieces) &&
2590 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002591 CastKind castKind =
2592 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2593 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002594 Exprs[InputOpNo] = InputExpr;
2595 NS->setInputExpr(i, InputExpr);
2596 continue;
2597 }
2598
Chris Lattner28b05c82009-05-03 06:50:40 +00002599 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002600 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002601 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002602 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002603 return StmtError();
2604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002606 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002607}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002608
John McCalldadc5752010-08-24 06:29:42 +00002609StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002610Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002611 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002612 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002613 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002614 if (Var && Var->isInvalidDecl())
2615 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616
John McCallb268a282010-08-23 23:25:46 +00002617 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002618}
2619
John McCalldadc5752010-08-24 06:29:42 +00002620StmtResult
John McCallb268a282010-08-23 23:25:46 +00002621Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2622 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002623}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002624
John McCalldadc5752010-08-24 06:29:42 +00002625StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002626Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002627 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002628 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002629 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2630
John McCallaab3e412010-08-25 08:40:02 +00002631 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002632 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002633 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2634 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002635 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002636 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002637}
2638
John McCalldadc5752010-08-24 06:29:42 +00002639StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00002640 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002641 if (Throw) {
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002642 Throw = MaybeCreateExprWithCleanups(Throw);
John Wiegley01296292011-04-08 18:41:53 +00002643 ExprResult Result = DefaultLvalueConversion(Throw);
2644 if (Result.isInvalid())
2645 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002646
John Wiegley01296292011-04-08 18:41:53 +00002647 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00002648 QualType ThrowType = Throw->getType();
2649 // Make sure the expression type is an ObjC pointer or "void *".
2650 if (!ThrowType->isDependentType() &&
2651 !ThrowType->isObjCObjectPointerType()) {
2652 const PointerType *PT = ThrowType->getAs<PointerType>();
2653 if (!PT || !PT->getPointeeType()->isVoidType())
2654 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2655 << Throw->getType() << Throw->getSourceRange());
2656 }
2657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
John McCallb268a282010-08-23 23:25:46 +00002659 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002660}
2661
John McCalldadc5752010-08-24 06:29:42 +00002662StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002664 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002665 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002666 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2667
John McCallb268a282010-08-23 23:25:46 +00002668 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002669 // @throw without an expression designates a rethrow (which much occur
2670 // in the context of an @catch clause).
2671 Scope *AtCatchParent = CurScope;
2672 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2673 AtCatchParent = AtCatchParent->getParent();
2674 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002675 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002676 }
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002677
John McCallb268a282010-08-23 23:25:46 +00002678 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002679}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002680
John McCalld9bb7432011-07-27 21:50:02 +00002681ExprResult
2682Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2683 ExprResult result = DefaultLvalueConversion(operand);
2684 if (result.isInvalid())
2685 return ExprError();
2686 operand = result.take();
2687
2688 // Make sure the expression type is an ObjC pointer or "void *".
2689 QualType type = operand->getType();
2690 if (!type->isDependentType() &&
2691 !type->isObjCObjectPointerType()) {
2692 const PointerType *pointerType = type->getAs<PointerType>();
2693 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2694 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2695 << type << operand->getSourceRange();
2696 }
2697
2698 // The operand to @synchronized is a full-expression.
2699 return MaybeCreateExprWithCleanups(operand);
2700}
2701
John McCalldadc5752010-08-24 06:29:42 +00002702StmtResult
John McCallb268a282010-08-23 23:25:46 +00002703Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2704 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002705 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002706 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002707 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002708}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002709
2710/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2711/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002712StmtResult
John McCall48871652010-08-21 09:40:31 +00002713Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002714 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002715 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002716 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002717 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002718 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002719}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002720
John McCall31168b02011-06-15 23:02:42 +00002721StmtResult
2722Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2723 getCurFunction()->setHasBranchProtectedScope();
2724 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2725}
2726
Dan Gohman28ade552010-07-26 21:25:24 +00002727namespace {
2728
Sebastian Redl63c4da02009-07-29 17:15:45 +00002729class TypeWithHandler {
2730 QualType t;
2731 CXXCatchStmt *stmt;
2732public:
2733 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2734 : t(type), stmt(statement) {}
2735
John McCall8ccfcb52009-09-24 19:53:00 +00002736 // An arbitrary order is fine as long as it places identical
2737 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002738 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002739 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002740 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002741 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002742 return false;
2743 else
2744 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2745 }
Mike Stump11289f42009-09-09 15:08:12 +00002746
Sebastian Redl63c4da02009-07-29 17:15:45 +00002747 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002748 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002749 }
Mike Stump11289f42009-09-09 15:08:12 +00002750
Sebastian Redl63c4da02009-07-29 17:15:45 +00002751 CXXCatchStmt *getCatchStmt() const { return stmt; }
2752 SourceLocation getTypeSpecStartLoc() const {
2753 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2754 }
2755};
2756
Dan Gohman28ade552010-07-26 21:25:24 +00002757}
2758
Sebastian Redl9b244a82008-12-22 21:35:02 +00002759/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2760/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002761StmtResult
John McCallb268a282010-08-23 23:25:46 +00002762Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002763 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002764 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002765 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002766 !getSourceManager().isInSystemHeader(TryLoc))
2767 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002768
Sebastian Redl9b244a82008-12-22 21:35:02 +00002769 unsigned NumHandlers = RawHandlers.size();
2770 assert(NumHandlers > 0 &&
2771 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002772 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002773
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002774 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002775
2776 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002777 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002778 if (!Handler->getExceptionDecl()) {
2779 if (i < NumHandlers - 1)
2780 return StmtError(Diag(Handler->getLocStart(),
2781 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002782
Sebastian Redl63c4da02009-07-29 17:15:45 +00002783 continue;
2784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Sebastian Redl63c4da02009-07-29 17:15:45 +00002786 const QualType CaughtType = Handler->getCaughtType();
2787 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2788 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002789 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002790
2791 // Detect handlers for the same type as an earlier one.
2792 if (NumHandlers > 1) {
2793 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002794
Sebastian Redl63c4da02009-07-29 17:15:45 +00002795 TypeWithHandler prev = TypesWithHandlers[0];
2796 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2797 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002798
Sebastian Redl63c4da02009-07-29 17:15:45 +00002799 if (curr == prev) {
2800 Diag(curr.getTypeSpecStartLoc(),
2801 diag::warn_exception_caught_by_earlier_handler)
2802 << curr.getCatchStmt()->getCaughtType().getAsString();
2803 Diag(prev.getTypeSpecStartLoc(),
2804 diag::note_previous_exception_handler)
2805 << prev.getCatchStmt()->getCaughtType().getAsString();
2806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Sebastian Redl63c4da02009-07-29 17:15:45 +00002808 prev = curr;
2809 }
2810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
John McCallaab3e412010-08-25 08:40:02 +00002812 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002813
Sebastian Redl9b244a82008-12-22 21:35:02 +00002814 // FIXME: We should detect handlers that cannot catch anything because an
2815 // earlier handler catches a superclass. Need to find a method that is not
2816 // quadratic for this.
2817 // Neither of these are explicitly forbidden, but every compiler detects them
2818 // and warns.
2819
John McCallb268a282010-08-23 23:25:46 +00002820 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002821 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002822}
John Wiegley1c0675e2011-04-28 01:08:34 +00002823
2824StmtResult
2825Sema::ActOnSEHTryBlock(bool IsCXXTry,
2826 SourceLocation TryLoc,
2827 Stmt *TryBlock,
2828 Stmt *Handler) {
2829 assert(TryBlock && Handler);
2830
2831 getCurFunction()->setHasBranchProtectedScope();
2832
2833 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2834}
2835
2836StmtResult
2837Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2838 Expr *FilterExpr,
2839 Stmt *Block) {
2840 assert(FilterExpr && Block);
2841
2842 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002843 return StmtError(Diag(FilterExpr->getExprLoc(),
2844 diag::err_filter_expression_integral)
2845 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002846 }
2847
2848 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2849}
2850
2851StmtResult
2852Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2853 Stmt *Block) {
2854 assert(Block);
2855 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2856}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00002857
2858StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2859 bool IsIfExists,
2860 NestedNameSpecifierLoc QualifierLoc,
2861 DeclarationNameInfo NameInfo,
2862 Stmt *Nested)
2863{
2864 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2865 QualifierLoc, NameInfo,
2866 cast<CompoundStmt>(Nested));
2867}
2868
2869
2870StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2871 bool IsIfExists,
2872 CXXScopeSpec &SS,
2873 UnqualifiedId &Name,
2874 Stmt *Nested) {
2875 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2876 SS.getWithLocInContext(Context),
2877 GetNameFromUnqualifiedId(Name),
2878 Nested);
2879}