blob: 79e317bb8caa29206e8db390ea2076ad02b29cca [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"
Anders Carlsson59689ed2008-11-22 21:04:56 +000019#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000027#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000028#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000029#include "llvm/ADT/ArrayRef.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000032using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000033using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000034
John McCalldadc5752010-08-24 06:29:42 +000035StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000036 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000037 if (!E) // FIXME: FullExprArg has no error state?
38 return StmtError();
39
Chris Lattner903eb512008-07-25 23:18:17 +000040 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41 // void expression for its side effects. Conversion to void allows any
42 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000043
Chris Lattner903eb512008-07-25 23:18:17 +000044 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000045 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000046}
47
48
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000049StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
50 SourceLocation LeadingEmptyMacroLoc) {
51 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc));
Chris Lattner0f203a72007-05-28 01:45:28 +000052}
53
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000054StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000056 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000057
Chris Lattnercbafe8d2009-04-12 20:13:14 +000058 // If we have an invalid decl, just return an error.
59 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner34a22092009-03-04 04:23:07 +000061 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000062}
Chris Lattneraf8d5812006-11-10 05:07:45 +000063
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000064void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000066
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000067 // If we have an invalid decl, just return.
68 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000069 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000071 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000072 var->setUsed();
73
John McCalld4631322011-06-17 06:42:21 +000074 // foreach variables are never actually initialized in the way that
75 // the parser came up with.
76 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000077
John McCalld4631322011-06-17 06:42:21 +000078 // In ARC, we don't need to retain the iteration variable of a fast
79 // enumeration loop. Rather than actually trying to catch that
80 // during declaration processing, we remove the consequences here.
81 if (getLangOptions().ObjCAutoRefCount) {
82 QualType type = var->getType();
83
84 // Only do this if we inferred the lifetime. Inferred lifetime
85 // will show up as a local qualifier because explicit lifetime
86 // should have shown up as an AttributedType instead.
87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
88 // Add 'const' and mark the variable as pseudo-strong.
89 var->setType(type.withConst());
90 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +000091 }
92 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000093}
94
Chandler Carruthae51ecc2011-08-17 08:38:04 +000095/// \brief Diagnose '==' and '!=' in top-level statements as likely
96/// typos for '=' or '|=' (resp.).
97///
98/// This function looks through common stand-alone statements to dig out the
99/// substatement of interest. It should be viable to call on any direct member
100/// of a CompoundStmt.
101///
102/// Adding a cast to void (or other expression wrappers) will prevent the
103/// warning from firing.
104static void DiagnoseTopLevelComparison(Sema &S, const Stmt *Statement) {
105 if (!Statement) return;
106 const Expr *E = dyn_cast<Expr>(Statement);
107 if (!E) {
108 // Descend to sub-statements where they remain "top-level" in that they're
109 // unused.
110 switch (Statement->getStmtClass()) {
111 default:
112 // Skip statements which don't have a direct substatement of interest.
113 // Compound statements are handled by the caller.
114 return;
115
116 case Stmt::CaseStmtClass:
117 case Stmt::DefaultStmtClass:
118 DiagnoseTopLevelComparison(S, cast<SwitchCase>(Statement)->getSubStmt());
119 return;
120 case Stmt::LabelStmtClass:
121 DiagnoseTopLevelComparison(S, cast<LabelStmt>(Statement)->getSubStmt());
122 return;
123
124 case Stmt::DoStmtClass:
125 DiagnoseTopLevelComparison(S, cast<DoStmt>(Statement)->getBody());
126 return;
127 case Stmt::IfStmtClass: {
128 const IfStmt *If = cast<IfStmt>(Statement);
129 DiagnoseTopLevelComparison(S, If->getThen());
130 DiagnoseTopLevelComparison(S, If->getElse());
131 return;
132 }
133 case Stmt::ForStmtClass: {
134 const ForStmt *ForLoop = cast<ForStmt>(Statement);
135 DiagnoseTopLevelComparison(S, ForLoop->getInit());
136 DiagnoseTopLevelComparison(S, ForLoop->getInc());
137 DiagnoseTopLevelComparison(S, ForLoop->getBody());
138 return;
139 }
140 case Stmt::SwitchStmtClass:
141 DiagnoseTopLevelComparison(S, cast<SwitchStmt>(Statement)->getBody());
142 return;
143 case Stmt::WhileStmtClass:
144 DiagnoseTopLevelComparison(S, cast<WhileStmt>(Statement)->getBody());
145 return;
146 }
147 }
148
149 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000150 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000151
152 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
153 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
154 return;
155
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000156 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000157 IsNotEqual = Op->getOpcode() == BO_NE;
158 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000159 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
160 if (Op->getOperator() != OO_EqualEqual &&
161 Op->getOperator() != OO_ExclaimEqual)
162 return;
163
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000164 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000165 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
166 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000167 } else {
168 // Not a typo-prone comparison.
169 return;
170 }
171
172 // Suppress warnings when the operator, suspicious as it may be, comes from
173 // a macro expansion.
174 if (Loc.isMacroID())
175 return;
176
177 S.Diag(Loc, diag::warn_comparison_top_level_stmt)
178 << (unsigned)IsNotEqual << E->getSourceRange();
179
180 SourceLocation Open = E->getSourceRange().getBegin();
181 SourceLocation Close = S.PP.getLocForEndOfToken(E->getSourceRange().getEnd());
182 S.Diag(Loc, diag::note_top_level_comparison_void_cast_silence)
183 << FixItHint::CreateInsertion(Open, "(void)(")
184 << FixItHint::CreateInsertion(Close, ")");
185
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
188 if (CanAssign) {
189 if (IsNotEqual)
190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
192 else
193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
195 }
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000196}
197
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000198void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000199 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
200 return DiagnoseUnusedExprResult(Label->getSubStmt());
201
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000202 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000203 if (!E)
204 return;
205
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000206 SourceLocation Loc;
207 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +0000208 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000209 return;
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000211 // Okay, we have an unused result. Depending on what the base expression is,
212 // we might want to make a more specific diagnostic. Check for one of these
213 // cases now.
214 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000215 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000216 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000217 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
218 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000219
John McCall34376a62010-12-04 03:47:34 +0000220 E = E->IgnoreParenImpCasts();
Chris Lattner1a6babf2009-10-13 04:53:48 +0000221 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000222 if (E->getType()->isVoidType())
223 return;
224
Chris Lattner1a6babf2009-10-13 04:53:48 +0000225 // If the callee has attribute pure, const, or warn_unused_result, warn with
226 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000227 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000228 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000229 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000230 return;
231 }
232 if (FD->getAttr<PureAttr>()) {
233 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
234 return;
235 }
236 if (FD->getAttr<ConstAttr>()) {
237 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
238 return;
239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240 }
John McCallb7bd14f2010-12-02 01:19:52 +0000241 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
John McCall31168b02011-06-15 23:02:42 +0000242 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
243 Diag(Loc, diag::err_arc_unused_init_message) << R1;
244 return;
245 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000246 const ObjCMethodDecl *MD = ME->getMethodDecl();
247 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000248 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000249 return;
250 }
John McCallb7bd14f2010-12-02 01:19:52 +0000251 } else if (isa<ObjCPropertyRefExpr>(E)) {
252 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000253 } else if (const CXXFunctionalCastExpr *FC
254 = dyn_cast<CXXFunctionalCastExpr>(E)) {
255 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
256 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
257 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000258 }
John McCall2351cb92010-04-06 22:24:14 +0000259 // Diagnose "(void*) blah" as a typo for "(void) blah".
260 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
261 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
262 QualType T = TI->getType();
263
264 // We really do want to use the non-canonical type here.
265 if (T == Context.VoidPtrTy) {
266 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
267
268 Diag(Loc, diag::warn_unused_voidptr)
269 << FixItHint::CreateRemoval(TL.getStarLoc());
270 return;
271 }
272 }
273
Ted Kremenek3427fac2011-02-23 01:52:04 +0000274 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000275}
276
John McCalldadc5752010-08-24 06:29:42 +0000277StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000278Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000279 MultiStmtArg elts, bool isStmtExpr) {
280 unsigned NumElts = elts.size();
281 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000282 // If we're in C89 mode, check that we don't have any decls after stmts. If
283 // so, emit an extension diagnostic.
284 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
285 // Note that __extension__ can be around a decl.
286 unsigned i = 0;
287 // Skip over all declarations.
288 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
289 /*empty*/;
290
291 // We found the end of the list or a statement. Scan for another declstmt.
292 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
293 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattnerd864daf2007-08-27 04:29:41 +0000295 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000296 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000297 Diag(D->getLocation(), diag::ext_mixed_decls_code);
298 }
299 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000300 // Warn about unused expressions in statements.
301 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000302 // Ignore statements that are last in a statement expression.
303 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000304 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000306 // FIXME: It'd be nice to not show both of these. The first is a more
307 // precise (and more likely to be enabled) warning. We should suppress the
308 // second when the first fires.
309 DiagnoseTopLevelComparison(*this, Elts[i]);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000310 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000311 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000312
Ted Kremenek5a201952009-02-07 01:47:29 +0000313 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000314}
315
John McCalldadc5752010-08-24 06:29:42 +0000316StmtResult
John McCallb268a282010-08-23 23:25:46 +0000317Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
318 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000319 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000320 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000321
Steve Naroff8eeeb132007-05-08 21:09:37 +0000322 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000323 // However, GCC allows any evaluatable integer expression.
Mike Stump11289f42009-09-09 15:08:12 +0000324 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000325 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000326 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000327
Chris Lattner46eeb222007-07-18 02:28:47 +0000328 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000329
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000330 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
331 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000332 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000333 }
334
John McCallaab3e412010-08-25 08:40:02 +0000335 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000336 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000337 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000338 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000339
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000340 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
341 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000342 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000343 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000344}
345
Chris Lattner34a22092009-03-04 04:23:07 +0000346/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000347void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner34a22092009-03-04 04:23:07 +0000348 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000349 CS->setSubStmt(SubStmt);
350}
351
John McCalldadc5752010-08-24 06:29:42 +0000352StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000353Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000354 Stmt *SubStmt, Scope *CurScope) {
John McCallaab3e412010-08-25 08:40:02 +0000355 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000356 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000357 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000358 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000359
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000360 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000361 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000362 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000363}
364
John McCalldadc5752010-08-24 06:29:42 +0000365StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000366Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
367 SourceLocation ColonLoc, Stmt *SubStmt) {
368
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000369 // If the label was multiply defined, reject it now.
370 if (TheDecl->getStmt()) {
371 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
372 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000373 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000374 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000375
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000376 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000377 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
378 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000379 if (!TheDecl->isGnuLocal())
380 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000381 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000382}
383
John McCalldadc5752010-08-24 06:29:42 +0000384StmtResult
John McCall48871652010-08-21 09:40:31 +0000385Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000386 Stmt *thenStmt, SourceLocation ElseLoc,
387 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000388 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000389
Douglas Gregor633caca2009-11-23 23:44:04 +0000390 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000391 if (CondVar) {
392 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000393 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000394 if (CondResult.isInvalid())
395 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000396 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000397 Expr *ConditionExpr = CondResult.takeAs<Expr>();
398 if (!ConditionExpr)
399 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000401 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000402
Anders Carlssondb83d772007-10-10 20:50:11 +0000403 // Warn if the if block has a null body without an else value.
404 // this helps prevent bugs due to typos, such as
405 // if (condition);
406 // do_stuff();
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000407 //
John McCallb268a282010-08-23 23:25:46 +0000408 if (!elseStmt) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000409 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidis90ee2a42010-11-19 20:54:25 +0000410 // But do not warn if the body is a macro that expands to nothing, e.g:
411 //
412 // #define CALL(x)
413 // if (condition)
414 // CALL(0);
415 //
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000416 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenek8eeec5b2010-09-16 00:37:05 +0000417 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000418 }
419
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000420 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000421
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000423 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000424}
Steve Naroff86272ea2007-05-29 02:14:17 +0000425
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000426/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
427/// the specified width and sign. If an overflow occurs, detect it and emit
428/// the specified diagnostic.
429void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
430 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000431 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000432 unsigned DiagID) {
433 // Perform a conversion to the promoted condition type if needed.
434 if (NewWidth > Val.getBitWidth()) {
435 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000436 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000437 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000438
439 // If the input was signed and negative and the output is
440 // unsigned, don't bother to warn: this is implementation-defined
441 // behavior.
442 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000443 } else if (NewWidth < Val.getBitWidth()) {
444 // If this is a truncation, check for overflow.
445 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000446 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000447 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000448 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000449 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000450 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000451 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000453 // Regardless of whether a diagnostic was emitted, really do the
454 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000455 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000456 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000457 } else if (NewSign != Val.isSigned()) {
458 // Convert the sign to match the sign of the condition. This can cause
459 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000460 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000461 // behavior.
462 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000463 llvm::APSInt OldVal(Val);
464 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000465 }
466}
467
Chris Lattner67998452007-08-23 18:29:20 +0000468namespace {
469 struct CaseCompareFunctor {
470 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
471 const llvm::APSInt &RHS) {
472 return LHS.first < RHS;
473 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000474 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
475 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
476 return LHS.first < RHS.first;
477 }
Chris Lattner67998452007-08-23 18:29:20 +0000478 bool operator()(const llvm::APSInt &LHS,
479 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
480 return LHS < RHS.first;
481 }
482 };
483}
484
Chris Lattner4b2ff022007-09-21 18:15:22 +0000485/// CmpCaseVals - Comparison predicate for sorting case values.
486///
487static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
488 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
489 if (lhs.first < rhs.first)
490 return true;
491
492 if (lhs.first == rhs.first &&
493 lhs.second->getCaseLoc().getRawEncoding()
494 < rhs.second->getCaseLoc().getRawEncoding())
495 return true;
496 return false;
497}
498
Douglas Gregorbd6839732010-02-08 22:24:16 +0000499/// CmpEnumVals - Comparison predicate for sorting enumeration values.
500///
501static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
502 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
503{
504 return lhs.first < rhs.first;
505}
506
507/// EqEnumVals - Comparison preficate for uniqing enumeration values.
508///
509static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
510 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
511{
512 return lhs.first == rhs.first;
513}
514
Chris Lattnera96d4272009-10-16 16:45:22 +0000515/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
516/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000517static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
518 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
519 expr = cleanups->getSubExpr();
520 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
521 if (impcast->getCastKind() != CK_IntegralCast) break;
522 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000523 }
524 return expr->getType();
525}
526
John McCalldadc5752010-08-24 06:29:42 +0000527StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000528Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000529 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000530 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000531
Douglas Gregore60e41a2010-05-06 17:25:47 +0000532 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000533 if (CondVar) {
534 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000535 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
536 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000537 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538
John McCallb268a282010-08-23 23:25:46 +0000539 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
John McCallb268a282010-08-23 23:25:46 +0000542 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000543 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544
John McCallb268a282010-08-23 23:25:46 +0000545 CondResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000546 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000547 PDiag(diag::err_typecheck_statement_requires_integer),
548 PDiag(diag::err_switch_incomplete_class_type)
John McCallb268a282010-08-23 23:25:46 +0000549 << Cond->getSourceRange(),
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000550 PDiag(diag::err_switch_explicit_conversion),
551 PDiag(diag::note_switch_conversion),
552 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000553 PDiag(diag::note_switch_conversion),
554 PDiag(0));
John McCallb268a282010-08-23 23:25:46 +0000555 if (CondResult.isInvalid()) return StmtError();
556 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
John McCall5939b162011-08-06 07:30:58 +0000558 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
559 CondResult = UsualUnaryConversions(Cond);
560 if (CondResult.isInvalid()) return StmtError();
561 Cond = CondResult.take();
562
John McCall48871652010-08-21 09:40:31 +0000563 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000564 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000565 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000566 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000567 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000568 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000569 }
John McCalla95172b2010-08-01 00:26:45 +0000570
John McCallaab3e412010-08-25 08:40:02 +0000571 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572
John McCallb268a282010-08-23 23:25:46 +0000573 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000574 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000575 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000576}
577
Gabor Greif16e02862010-10-01 22:05:14 +0000578static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
579 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000580 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000581 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000582 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000583 Val.setIsSigned(IsSigned);
584}
585
John McCalldadc5752010-08-24 06:29:42 +0000586StmtResult
John McCallb268a282010-08-23 23:25:46 +0000587Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
588 Stmt *BodyStmt) {
589 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000590 assert(SS == getCurFunction()->SwitchStack.back() &&
591 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000592
Steve Naroff42a350a2007-09-01 21:08:38 +0000593 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000594 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000595
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000596 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000597 if (!CondExpr) return StmtError();
598
599 QualType CondType = CondExpr->getType();
600
John McCalld3dfbd62010-05-18 03:19:21 +0000601 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000602 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000603 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000604
Chris Lattnera96d4272009-10-16 16:45:22 +0000605 // C++ 6.4.2.p2:
606 // Integral promotions are performed (on the switch condition).
607 //
608 // A case value unrepresentable by the original switch condition
609 // type (before the promotion) doesn't make sense, even when it can
610 // be represented by the promoted type. Therefore we need to find
611 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000612 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000613 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000615 // appropriate type now, just return an error.
616 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000617 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000618
Chris Lattner4ebae652010-04-16 23:34:13 +0000619 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000620 // switch(bool_expr) {...} is often a programmer error, e.g.
621 // switch(n && mask) { ... } // Doh - should be "n & mask".
622 // One can always use an if statement instead of switch(bool_expr).
623 Diag(SwitchLoc, diag::warn_bool_switch_condition)
624 << CondExpr->getSourceRange();
625 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000626 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000627
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000628 // Get the bitwidth of the switched-on value before promotions. We must
629 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000630 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000631 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000632 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000633 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000634 bool CondIsSigned
635 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000637 // Accumulate all of the case values in a vector so that we can sort them
638 // and detect duplicates. This vector contains the APInt for the case after
639 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000640 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000641 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000642
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000643 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000644 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
645 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000647 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner10cb5e52007-08-23 06:23:56 +0000649 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000650
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000651 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000652 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000653
Anders Carlsson51873c22007-07-22 07:07:56 +0000654 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000655 if (TheDefaultStmt) {
656 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000657 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000658
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000659 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000660 // we'll return a valid AST. This requires recursing down the AST and
661 // finding it, not something we are set up to do right now. For now,
662 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000663 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000664 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000665 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000667 } else {
668 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000670 // We already verified that the expression has a i-c-e value (C99
671 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000672 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000673
674 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
675 HasDependentValue = true;
676 break;
677 }
Mike Stump11289f42009-09-09 15:08:12 +0000678
Anders Carlsson59689ed2008-11-22 21:04:56 +0000679 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000681 // Convert the value to the same width/sign as the condition.
682 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000683 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000684 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000685
Chris Lattnera65e1f32008-01-16 19:17:22 +0000686 // If the LHS is not the same type as the condition, insert an implicit
687 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000688 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
Chris Lattnera65e1f32008-01-16 19:17:22 +0000689 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000690
Chris Lattner10cb5e52007-08-23 06:23:56 +0000691 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000692 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000693 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000694 CS->getRHS()->isValueDependent()) {
695 HasDependentValue = true;
696 break;
697 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000698 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000699 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000700 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000701 }
702 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000703
704 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000705 // If we don't have a default statement, check whether the
706 // condition is constant.
707 llvm::APSInt ConstantCondValue;
708 bool HasConstantCond = false;
709 bool ShouldCheckConstantCond = false;
710 if (!HasDependentValue && !TheDefaultStmt) {
711 Expr::EvalResult Result;
712 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
713 if (HasConstantCond) {
714 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
715 ConstantCondValue = Result.Val.getInt();
716 ShouldCheckConstantCond = true;
717
718 assert(ConstantCondValue.getBitWidth() == CondWidth &&
719 ConstantCondValue.isSigned() == CondIsSigned);
720 }
721 }
722
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000723 // Sort all the scalar case values so we can easily detect duplicates.
724 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
725
726 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000727 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
728 if (ShouldCheckConstantCond &&
729 CaseVals[i].first == ConstantCondValue)
730 ShouldCheckConstantCond = false;
731
732 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000733 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000734 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000735 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
736 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000737 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000738 // FIXME: We really want to remove the bogus case stmt from the
739 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000740 CaseListIsErroneous = true;
741 }
742 }
743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000745 // Detect duplicate case ranges, which usually don't exist at all in
746 // the first place.
747 if (!CaseRanges.empty()) {
748 // Sort all the case ranges by their low value so we can easily detect
749 // overlaps between ranges.
750 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000752 // Scan the ranges, computing the high values and removing empty ranges.
753 std::vector<llvm::APSInt> HiVals;
754 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000755 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000756 CaseStmt *CR = CaseRanges[i].second;
757 Expr *Hi = CR->getRHS();
758 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000759
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000760 // Convert the value to the same width/sign as the condition.
761 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000762 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000763 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000764
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000765 // If the LHS is not the same type as the condition, insert an implicit
766 // cast.
John Wiegley01296292011-04-08 18:41:53 +0000767 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000768 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000770 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000771 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000772 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
773 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000774 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000775 CaseRanges.erase(CaseRanges.begin()+i);
776 --i, --e;
777 continue;
778 }
John McCalld3dfbd62010-05-18 03:19:21 +0000779
780 if (ShouldCheckConstantCond &&
781 LoVal <= ConstantCondValue &&
782 ConstantCondValue <= HiVal)
783 ShouldCheckConstantCond = false;
784
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000785 HiVals.push_back(HiVal);
786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000788 // Rescan the ranges, looking for overlap with singleton values and other
789 // ranges. Since the range list is sorted, we only need to compare case
790 // ranges with their neighbors.
791 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
792 llvm::APSInt &CRLo = CaseRanges[i].first;
793 llvm::APSInt &CRHi = HiVals[i];
794 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000796 // Check to see whether the case range overlaps with any
797 // singleton cases.
798 CaseStmt *OverlapStmt = 0;
799 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000800
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000801 // Find the smallest value >= the lower bound. If I is in the
802 // case range, then we have overlap.
803 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
804 CaseVals.end(), CRLo,
805 CaseCompareFunctor());
806 if (I != CaseVals.end() && I->first < CRHi) {
807 OverlapVal = I->first; // Found overlap with scalar.
808 OverlapStmt = I->second;
809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000811 // Find the smallest value bigger than the upper bound.
812 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
813 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
814 OverlapVal = (I-1)->first; // Found overlap with scalar.
815 OverlapStmt = (I-1)->second;
816 }
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000818 // Check to see if this case stmt overlaps with the subsequent
819 // case range.
820 if (i && CRLo <= HiVals[i-1]) {
821 OverlapVal = HiVals[i-1]; // Found overlap with range.
822 OverlapStmt = CaseRanges[i-1].second;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000825 if (OverlapStmt) {
826 // If we have a duplicate, report it.
827 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
828 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000829 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000830 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000831 // FIXME: We really want to remove the bogus case stmt from the
832 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000833 CaseListIsErroneous = true;
834 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000835 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000836 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000837
John McCalld3dfbd62010-05-18 03:19:21 +0000838 // Complain if we have a constant condition and we didn't find a match.
839 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
840 // TODO: it would be nice if we printed enums as enums, chars as
841 // chars, etc.
842 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
843 << ConstantCondValue.toString(10)
844 << CondExpr->getSourceRange();
845 }
846
847 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000848 // values. We only issue a warning if there is not 'default:', but
849 // we still do the analysis to preserve this information in the AST
850 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000851 //
Chris Lattner51679082010-09-16 17:09:42 +0000852 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000853
Douglas Gregorbd6839732010-02-08 22:24:16 +0000854 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000855 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000856 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000857 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000858 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000859 EnumValsTy EnumVals;
860
John McCalld3dfbd62010-05-18 03:19:21 +0000861 // Gather all enum values, set their type and sort them,
862 // allowing easier comparison with CaseVals.
863 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000864 EDI != ED->enumerator_end(); ++EDI) {
865 llvm::APSInt Val = EDI->getInitVal();
866 AdjustAPSInt(Val, CondWidth, CondIsSigned);
867 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000868 }
869 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000870 EnumValsTy::iterator EIend =
871 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000872
873 // See which case values aren't in enum.
874 // TODO: we might want to check whether case values are out of the
875 // enum even if we don't want to check whether all cases are handled.
876 if (!TheDefaultStmt) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000877 EnumValsTy::const_iterator EI = EnumVals.begin();
878 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000879 CI != CaseVals.end(); CI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000880 while (EI != EIend && EI->first < CI->first)
881 EI++;
882 if (EI == EIend || EI->first > CI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000883 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
884 << ED->getDeclName();
Ted Kremenek02627a22010-09-09 06:53:59 +0000885 }
886 // See which of case ranges aren't in enum
887 EI = EnumVals.begin();
888 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000889 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000890 while (EI != EIend && EI->first < RI->first)
891 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Ted Kremenek02627a22010-09-09 06:53:59 +0000893 if (EI == EIend || EI->first != RI->first) {
894 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
895 << ED->getDeclName();
896 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000897
Ted Kremenek02627a22010-09-09 06:53:59 +0000898 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000899 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek02627a22010-09-09 06:53:59 +0000900 while (EI != EIend && EI->first < Hi)
901 EI++;
902 if (EI == EIend || EI->first != Hi)
903 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
904 << ED->getDeclName();
905 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907
Ted Kremenekc42f3452010-09-09 00:05:53 +0000908 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +0000909 CaseValsTy::const_iterator CI = CaseVals.begin();
910 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000911 bool hasCasesNotInSwitch = false;
912
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000913 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914
Ted Kremenekc42f3452010-09-09 00:05:53 +0000915 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +0000916 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +0000917 llvm::APSInt CIVal;
918 while (CI != CaseVals.end() && CI->first < EI->first)
919 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
Douglas Gregorbd6839732010-02-08 22:24:16 +0000921 if (CI != CaseVals.end() && CI->first == EI->first)
922 continue;
923
Ted Kremenekc42f3452010-09-09 00:05:53 +0000924 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +0000925 for (; RI != CaseRanges.end(); RI++) {
926 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +0000927 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000928 if (EI->first <= Hi)
929 break;
930 }
931
Ted Kremenekc42f3452010-09-09 00:05:53 +0000932 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +0000933 hasCasesNotInSwitch = true;
934 if (!TheDefaultStmt)
Chris Lattner51679082010-09-16 17:09:42 +0000935 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +0000936 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000937 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938
Chris Lattner51679082010-09-16 17:09:42 +0000939 // Produce a nice diagnostic if multiple values aren't handled.
940 switch (UnhandledNames.size()) {
941 case 0: break;
942 case 1:
943 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
944 << UnhandledNames[0];
945 break;
946 case 2:
947 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
948 << UnhandledNames[0] << UnhandledNames[1];
949 break;
950 case 3:
951 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
952 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
953 break;
954 default:
955 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
956 << (unsigned)UnhandledNames.size()
957 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
958 break;
959 }
Ted Kremenekc42f3452010-09-09 00:05:53 +0000960
961 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +0000962 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000963 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000964 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000965
Mike Stump87c57ac2009-05-16 07:39:55 +0000966 // FIXME: If the case list was broken is some way, we don't have a good system
967 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000968 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000969 return StmtError();
970
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000971 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000972}
973
John McCalldadc5752010-08-24 06:29:42 +0000974StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +0000976 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +0000977 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978
Douglas Gregor680f8612009-11-24 21:15:44 +0000979 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000980 if (CondVar) {
981 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000982 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000983 if (CondResult.isInvalid())
984 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000985 }
John McCallb268a282010-08-23 23:25:46 +0000986 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000987 if (!ConditionExpr)
988 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
John McCallb268a282010-08-23 23:25:46 +0000990 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000992 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +0000993 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000994}
995
John McCalldadc5752010-08-24 06:29:42 +0000996StmtResult
John McCallb268a282010-08-23 23:25:46 +0000997Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000998 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +0000999 Expr *Cond, SourceLocation CondRParen) {
1000 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001001
John Wiegley01296292011-04-08 18:41:53 +00001002 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1003 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001004 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001005 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001006
John McCallacf0ee52010-10-08 02:01:28 +00001007 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001008 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001009 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001010 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001011 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
John McCallb268a282010-08-23 23:25:46 +00001013 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001014
John McCallb268a282010-08-23 23:25:46 +00001015 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001016}
1017
John McCalldadc5752010-08-24 06:29:42 +00001018StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001019Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001020 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001021 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001022 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001023 if (!getLangOptions().CPlusPlus) {
1024 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001025 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1026 // declare identifiers for objects having storage class 'auto' or
1027 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001028 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1029 DI!=DE; ++DI) {
1030 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001031 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001032 VD = 0;
1033 if (VD == 0)
1034 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1035 // FIXME: mark decl erroneous!
1036 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001037 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001038 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001039
John McCalldadc5752010-08-24 06:29:42 +00001040 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001041 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001042 if (secondVar) {
1043 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001044 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001045 if (SecondResult.isInvalid())
1046 return StmtError();
1047 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001049 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001050
Anders Carlsson1682af52009-08-01 01:39:59 +00001051 DiagnoseUnusedExprResult(First);
1052 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001053 DiagnoseUnusedExprResult(Body);
1054
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001055 return Owned(new (Context) ForStmt(Context, First,
1056 SecondResult.take(), ConditionVar,
1057 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001058 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001059}
1060
John McCall34376a62010-12-04 03:47:34 +00001061/// In an Objective C collection iteration statement:
1062/// for (x in y)
1063/// x can be an arbitrary l-value expression. Bind it up as a
1064/// full-expression.
1065StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1066 CheckImplicitConversions(E);
John McCall5d413782010-12-06 08:20:24 +00001067 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCall34376a62010-12-04 03:47:34 +00001068 if (Result.isInvalid()) return StmtError();
1069 return Owned(static_cast<Stmt*>(Result.get()));
1070}
1071
John McCall53848232011-07-27 01:07:15 +00001072ExprResult
1073Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1074 assert(collection);
1075
1076 // Bail out early if we've got a type-dependent expression.
1077 if (collection->isTypeDependent()) return Owned(collection);
1078
1079 // Perform normal l-value conversion.
1080 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1081 if (result.isInvalid())
1082 return ExprError();
1083 collection = result.take();
1084
1085 // The operand needs to have object-pointer type.
1086 // TODO: should we do a contextual conversion?
1087 const ObjCObjectPointerType *pointerType =
1088 collection->getType()->getAs<ObjCObjectPointerType>();
1089 if (!pointerType)
1090 return Diag(forLoc, diag::err_collection_expr_type)
1091 << collection->getType() << collection->getSourceRange();
1092
1093 // Check that the operand provides
1094 // - countByEnumeratingWithState:objects:count:
1095 const ObjCObjectType *objectType = pointerType->getObjectType();
1096 ObjCInterfaceDecl *iface = objectType->getInterface();
1097
1098 // If we have a forward-declared type, we can't do this check.
1099 if (iface && iface->isForwardDecl()) {
1100 // This is ill-formed under ARC.
1101 if (getLangOptions().ObjCAutoRefCount) {
1102 Diag(forLoc, diag::err_arc_collection_forward)
1103 << pointerType->getPointeeType() << collection->getSourceRange();
1104 }
1105
1106 // Otherwise, if we have any useful type information, check that
1107 // the type declares the appropriate method.
1108 } else if (iface || !objectType->qual_empty()) {
1109 IdentifierInfo *selectorIdents[] = {
1110 &Context.Idents.get("countByEnumeratingWithState"),
1111 &Context.Idents.get("objects"),
1112 &Context.Idents.get("count")
1113 };
1114 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1115
1116 ObjCMethodDecl *method = 0;
1117
1118 // If there's an interface, look in both the public and private APIs.
1119 if (iface) {
1120 method = iface->lookupInstanceMethod(selector);
1121 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1122 }
1123
1124 // Also check protocol qualifiers.
1125 if (!method)
1126 method = LookupMethodInQualifiedType(selector, pointerType,
1127 /*instance*/ true);
1128
1129 // If we didn't find it anywhere, give up.
1130 if (!method) {
1131 Diag(forLoc, diag::warn_collection_expr_type)
1132 << collection->getType() << selector << collection->getSourceRange();
1133 }
1134
1135 // TODO: check for an incompatible signature?
1136 }
1137
1138 // Wrap up any cleanups in the expression.
1139 return Owned(MaybeCreateExprWithCleanups(collection));
1140}
1141
John McCalldadc5752010-08-24 06:29:42 +00001142StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001143Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1144 SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001145 Stmt *First, Expr *Second,
1146 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian93977672008-01-10 20:33:58 +00001147 if (First) {
1148 QualType FirstType;
1149 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001150 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001151 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1152 diag::err_toomany_element_decls));
1153
John McCall31168b02011-06-15 23:02:42 +00001154 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1155 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001156 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1157 // declare identifiers for objects having storage class 'auto' or
1158 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001159 if (!D->hasLocalStorage())
1160 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001161 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001162 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001163 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001164 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001165 return StmtError(Diag(First->getLocStart(),
1166 diag::err_selector_element_not_lvalue)
1167 << First->getSourceRange());
1168
Mike Stump11289f42009-09-09 15:08:12 +00001169 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001170 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001171 if (!FirstType->isDependentType() &&
1172 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001173 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001174 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001175 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001176 }
John McCall53848232011-07-27 01:07:15 +00001177
Ted Kremenek5a201952009-02-07 01:47:29 +00001178 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1179 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001180}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001181
Richard Smith02e85f32011-04-14 22:09:26 +00001182namespace {
1183
1184enum BeginEndFunction {
1185 BEF_begin,
1186 BEF_end
1187};
1188
1189/// Build a variable declaration for a for-range statement.
1190static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1191 QualType Type, const char *Name) {
1192 DeclContext *DC = SemaRef.CurContext;
1193 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1194 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1195 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1196 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001197 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001198 return Decl;
1199}
1200
1201/// Finish building a variable declaration for a for-range statement.
1202/// \return true if an error occurs.
1203static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1204 SourceLocation Loc, int diag) {
1205 // Deduce the type for the iterator variable now rather than leaving it to
1206 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1207 TypeSourceInfo *InitTSI = 0;
1208 if (Init->getType()->isVoidType() ||
1209 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1210 SemaRef.Diag(Loc, diag) << Init->getType();
1211 if (!InitTSI) {
1212 Decl->setInvalidDecl();
1213 return true;
1214 }
1215 Decl->setTypeSourceInfo(InitTSI);
1216 Decl->setType(InitTSI->getType());
1217
John McCall31168b02011-06-15 23:02:42 +00001218 // In ARC, infer lifetime.
1219 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1220 // we're doing the equivalent of fast iteration.
1221 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1222 SemaRef.inferObjCARCLifetime(Decl))
1223 Decl->setInvalidDecl();
1224
Richard Smith02e85f32011-04-14 22:09:26 +00001225 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1226 /*TypeMayContainAuto=*/false);
1227 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001228 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001229 return false;
1230}
1231
1232/// Produce a note indicating which begin/end function was implicitly called
1233/// by a C++0x for-range statement. This is often not obvious from the code,
1234/// nor from the diagnostics produced when analysing the implicit expressions
1235/// required in a for-range statement.
1236void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1237 BeginEndFunction BEF) {
1238 CallExpr *CE = dyn_cast<CallExpr>(E);
1239 if (!CE)
1240 return;
1241 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1242 if (!D)
1243 return;
1244 SourceLocation Loc = D->getLocation();
1245
1246 std::string Description;
1247 bool IsTemplate = false;
1248 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1249 Description = SemaRef.getTemplateArgumentBindingsText(
1250 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1251 IsTemplate = true;
1252 }
1253
1254 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1255 << BEF << IsTemplate << Description << E->getType();
1256}
1257
1258/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1259/// given LookupResult is non-empty, it is assumed to describe a member which
1260/// will be invoked. Otherwise, the function will be found via argument
1261/// dependent lookup.
1262static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1263 SourceLocation Loc,
1264 VarDecl *Decl,
1265 BeginEndFunction BEF,
1266 const DeclarationNameInfo &NameInfo,
1267 LookupResult &MemberLookup,
1268 Expr *Range) {
1269 ExprResult CallExpr;
1270 if (!MemberLookup.empty()) {
1271 ExprResult MemberRef =
1272 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1273 /*IsPtr=*/false, CXXScopeSpec(),
1274 /*Qualifier=*/0, MemberLookup,
1275 /*TemplateArgs=*/0);
1276 if (MemberRef.isInvalid())
1277 return ExprError();
1278 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1279 Loc, 0);
1280 if (CallExpr.isInvalid())
1281 return ExprError();
1282 } else {
1283 UnresolvedSet<0> FoundNames;
1284 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1285 // std is an associated namespace.
1286 UnresolvedLookupExpr *Fn =
1287 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1288 NestedNameSpecifierLoc(), NameInfo,
1289 /*NeedsADL=*/true, /*Overloaded=*/false,
1290 FoundNames.begin(), FoundNames.end(),
1291 /*LookInStdNamespace=*/true);
1292 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1293 0);
1294 if (CallExpr.isInvalid()) {
1295 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1296 << Range->getType();
1297 return ExprError();
1298 }
1299 }
1300 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1301 diag::err_for_range_iter_deduction_failure)) {
1302 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1303 return ExprError();
1304 }
1305 return CallExpr;
1306}
1307
1308}
1309
1310/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1311///
1312/// C++0x [stmt.ranged]:
1313/// A range-based for statement is equivalent to
1314///
1315/// {
1316/// auto && __range = range-init;
1317/// for ( auto __begin = begin-expr,
1318/// __end = end-expr;
1319/// __begin != __end;
1320/// ++__begin ) {
1321/// for-range-declaration = *__begin;
1322/// statement
1323/// }
1324/// }
1325///
1326/// The body of the loop is not available yet, since it cannot be analysed until
1327/// we have determined the type of the for-range-declaration.
1328StmtResult
1329Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1330 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1331 SourceLocation RParenLoc) {
1332 if (!First || !Range)
1333 return StmtError();
1334
1335 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1336 assert(DS && "first part of for range not a decl stmt");
1337
1338 if (!DS->isSingleDecl()) {
1339 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1340 return StmtError();
1341 }
1342 if (DS->getSingleDecl()->isInvalidDecl())
1343 return StmtError();
1344
1345 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1346 return StmtError();
1347
1348 // Build auto && __range = range-init
1349 SourceLocation RangeLoc = Range->getLocStart();
1350 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1351 Context.getAutoRRefDeductType(),
1352 "__range");
1353 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1354 diag::err_for_range_deduction_failure))
1355 return StmtError();
1356
1357 // Claim the type doesn't contain auto: we've already done the checking.
1358 DeclGroupPtrTy RangeGroup =
1359 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1360 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1361 if (RangeDecl.isInvalid())
1362 return StmtError();
1363
1364 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1365 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1366 RParenLoc);
1367}
1368
1369/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1370StmtResult
1371Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1372 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1373 Expr *Inc, Stmt *LoopVarDecl,
1374 SourceLocation RParenLoc) {
1375 Scope *S = getCurScope();
1376
1377 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1378 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1379 QualType RangeVarType = RangeVar->getType();
1380
1381 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1382 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1383
1384 StmtResult BeginEndDecl = BeginEnd;
1385 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1386
1387 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1388 SourceLocation RangeLoc = RangeVar->getLocation();
1389
1390 ExprResult RangeRef = BuildDeclRefExpr(RangeVar,
1391 RangeVarType.getNonReferenceType(),
1392 VK_LValue, ColonLoc);
1393 if (RangeRef.isInvalid())
1394 return StmtError();
1395
1396 QualType AutoType = Context.getAutoDeductType();
1397 Expr *Range = RangeVar->getInit();
1398 if (!Range)
1399 return StmtError();
1400 QualType RangeType = Range->getType();
1401
1402 if (RequireCompleteType(RangeLoc, RangeType,
1403 PDiag(diag::err_for_range_incomplete_type)))
1404 return StmtError();
1405
1406 // Build auto __begin = begin-expr, __end = end-expr.
1407 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1408 "__begin");
1409 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1410 "__end");
1411
1412 // Build begin-expr and end-expr and attach to __begin and __end variables.
1413 ExprResult BeginExpr, EndExpr;
1414 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1415 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1416 // __range + __bound, respectively, where __bound is the array bound. If
1417 // _RangeT is an array of unknown size or an array of incomplete type,
1418 // the program is ill-formed;
1419
1420 // begin-expr is __range.
1421 BeginExpr = RangeRef;
1422 if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc,
1423 diag::err_for_range_iter_deduction_failure)) {
1424 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1425 return StmtError();
1426 }
1427
1428 // Find the array bound.
1429 ExprResult BoundExpr;
1430 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1431 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001432 Context.getPointerDiffType(),
1433 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001434 else if (const VariableArrayType *VAT =
1435 dyn_cast<VariableArrayType>(UnqAT))
1436 BoundExpr = VAT->getSizeExpr();
1437 else {
1438 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1439 // UnqAT is not incomplete and Range is not type-dependent.
1440 assert(0 && "Unexpected array type in for-range");
1441 return StmtError();
1442 }
1443
1444 // end-expr is __range + __bound.
1445 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(),
1446 BoundExpr.get());
1447 if (EndExpr.isInvalid())
1448 return StmtError();
1449 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1450 diag::err_for_range_iter_deduction_failure)) {
1451 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1452 return StmtError();
1453 }
1454 } else {
1455 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1456 ColonLoc);
1457 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1458 ColonLoc);
1459
1460 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1461 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1462
1463 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1464 // - if _RangeT is a class type, the unqualified-ids begin and end are
1465 // looked up in the scope of class _RangeT as if by class member access
1466 // lookup (3.4.5), and if either (or both) finds at least one
1467 // declaration, begin-expr and end-expr are __range.begin() and
1468 // __range.end(), respectively;
1469 LookupQualifiedName(BeginMemberLookup, D);
1470 LookupQualifiedName(EndMemberLookup, D);
1471
1472 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1473 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1474 << RangeType << BeginMemberLookup.empty();
1475 return StmtError();
1476 }
1477 } else {
1478 // - otherwise, begin-expr and end-expr are begin(__range) and
1479 // end(__range), respectively, where begin and end are looked up with
1480 // argument-dependent lookup (3.4.2). For the purposes of this name
1481 // lookup, namespace std is an associated namespace.
1482 }
1483
1484 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1485 BEF_begin, BeginNameInfo,
1486 BeginMemberLookup, RangeRef.get());
1487 if (BeginExpr.isInvalid())
1488 return StmtError();
1489
1490 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1491 BEF_end, EndNameInfo,
1492 EndMemberLookup, RangeRef.get());
1493 if (EndExpr.isInvalid())
1494 return StmtError();
1495 }
1496
1497 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1498 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1499 if (!Context.hasSameType(BeginType, EndType)) {
1500 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1501 << BeginType << EndType;
1502 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1503 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1504 }
1505
1506 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1507 // Claim the type doesn't contain auto: we've already done the checking.
1508 DeclGroupPtrTy BeginEndGroup =
1509 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1510 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1511
1512 ExprResult BeginRef = BuildDeclRefExpr(BeginVar,
1513 BeginType.getNonReferenceType(),
1514 VK_LValue, ColonLoc);
1515 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1516 VK_LValue, ColonLoc);
1517
1518 // Build and check __begin != __end expression.
1519 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1520 BeginRef.get(), EndRef.get());
1521 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1522 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1523 if (NotEqExpr.isInvalid()) {
1524 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1525 if (!Context.hasSameType(BeginType, EndType))
1526 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1527 return StmtError();
1528 }
1529
1530 // Build and check ++__begin expression.
1531 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1532 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1533 if (IncrExpr.isInvalid()) {
1534 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1535 return StmtError();
1536 }
1537
1538 // Build and check *__begin expression.
1539 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1540 if (DerefExpr.isInvalid()) {
1541 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1542 return StmtError();
1543 }
1544
1545 // Attach *__begin as initializer for VD.
1546 if (!LoopVar->isInvalidDecl()) {
1547 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1548 /*TypeMayContainAuto=*/true);
1549 if (LoopVar->isInvalidDecl())
1550 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1551 }
Richard Smithf9603352011-06-21 23:07:19 +00001552 } else {
1553 // The range is implicitly used as a placeholder when it is dependent.
1554 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001555 }
1556
1557 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1558 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1559 NotEqExpr.take(), IncrExpr.take(),
1560 LoopVarDS, /*Body=*/0, ForLoc,
1561 ColonLoc, RParenLoc));
1562}
1563
1564/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1565/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1566/// body cannot be performed until after the type of the range variable is
1567/// determined.
1568StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1569 if (!S || !B)
1570 return StmtError();
1571
1572 cast<CXXForRangeStmt>(S)->setBody(B);
1573 return S;
1574}
1575
Chris Lattnercab02a62011-02-17 20:34:02 +00001576StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1577 SourceLocation LabelLoc,
1578 LabelDecl *TheDecl) {
1579 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001580 TheDecl->setUsed();
1581 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001582}
Chris Lattner1c310502007-05-31 06:00:00 +00001583
John McCalldadc5752010-08-24 06:29:42 +00001584StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00001585Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00001586 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00001587 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00001588 if (!E->isTypeDependent()) {
1589 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00001590 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00001591 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00001592 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00001593 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1594 if (ExprRes.isInvalid())
1595 return StmtError();
1596 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00001597 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00001598 return StmtError();
1599 }
John McCalla95172b2010-08-01 00:26:45 +00001600
John McCallaab3e412010-08-25 08:40:02 +00001601 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00001602
Douglas Gregor30776d42009-05-16 00:20:29 +00001603 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001604}
1605
John McCalldadc5752010-08-24 06:29:42 +00001606StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001607Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001608 Scope *S = CurScope->getContinueParent();
1609 if (!S) {
1610 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001611 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001612 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001613
Ted Kremenek5a201952009-02-07 01:47:29 +00001614 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001615}
1616
John McCalldadc5752010-08-24 06:29:42 +00001617StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001618Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001619 Scope *S = CurScope->getBreakParent();
1620 if (!S) {
1621 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001622 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001623 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001624
Ted Kremenek5a201952009-02-07 01:47:29 +00001625 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001626}
1627
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001628/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00001629/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001630///
Douglas Gregor5d369002011-01-21 18:05:27 +00001631/// \param ReturnType If we're determining the copy elision candidate for
1632/// a return statement, this is the return type of the function. If we're
1633/// determining the copy elision candidate for a throw expression, this will
1634/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001635///
Douglas Gregor5d369002011-01-21 18:05:27 +00001636/// \param E The expression being returned from the function or block, or
1637/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001638///
Douglas Gregor86394412011-05-20 15:00:53 +00001639/// \param AllowFunctionParameter Whether we allow function parameters to
1640/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1641/// we re-use this logic to determine whether we should try to move as part of
1642/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001643///
1644/// \returns The NRVO candidate variable, if the return statement may use the
1645/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00001646const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1647 Expr *E,
1648 bool AllowFunctionParameter) {
1649 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001650 // - in a return statement in a function with ...
1651 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00001652 if (!ReturnType.isNull()) {
1653 if (!ReturnType->isRecordType())
1654 return 0;
1655 // ... the same cv-unqualified type as the function return type ...
1656 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1657 return 0;
1658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001659
1660 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00001661 // (other than a function or catch-clause parameter)) ...
1662 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001663 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001664 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001665 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1666 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001667 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001668
Douglas Gregor5d369002011-01-21 18:05:27 +00001669 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregor290c93e2010-05-15 06:46:45 +00001670 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregor5d369002011-01-21 18:05:27 +00001671 !VD->getType().isVolatileQualified() &&
Douglas Gregor732abf12011-01-21 18:20:49 +00001672 ((VD->getKind() == Decl::Var) ||
1673 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001674 return VD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001676 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001677}
1678
Douglas Gregor626fbed2011-01-21 21:08:57 +00001679/// \brief Perform the initialization of a potentially-movable value, which
1680/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00001681///
1682/// This routine implements C++0x [class.copy]p33, which attempts to treat
1683/// returned lvalues as rvalues in certain cases (to prefer move construction),
1684/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001685ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00001686Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1687 const VarDecl *NRVOCandidate,
1688 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001689 Expr *Value,
1690 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001691 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692 // When the criteria for elision of a copy operation are met or would
1693 // be met save for the fact that the source object is a function
1694 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00001695 // overload resolution to select the constructor for the copy is first
1696 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00001697 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001698 if (AllowNRVO &&
1699 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001701 Value->getType(), CK_LValueToRValue,
1702 Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703
Douglas Gregorf282a762011-01-21 19:38:21 +00001704 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00001706 = InitializationKind::CreateCopy(Value->getLocStart(),
1707 Value->getLocStart());
1708 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001709
1710 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00001711 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001712 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00001713 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001714 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00001715 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1716 StepEnd = Seq.step_end();
1717 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001718 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00001719 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001720
1721 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00001722 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001723
Douglas Gregorf282a762011-01-21 19:38:21 +00001724 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00001725 = Constructor->getParamDecl(0)->getType()
1726 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregorf282a762011-01-21 19:38:21 +00001728 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001729 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00001730 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1731 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00001732 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733
Douglas Gregorf282a762011-01-21 19:38:21 +00001734 // Promote "AsRvalue" to the heap, since we now need this
1735 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001736 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 CK_LValueToRValue, Value, 0,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001738 VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739
Douglas Gregorf282a762011-01-21 19:38:21 +00001740 // Complete type-checking the initialization of the return type
1741 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00001742 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00001743 }
1744 }
1745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Douglas Gregorf282a762011-01-21 19:38:21 +00001747 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00001749 // (again) now with the return value expression as written.
1750 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00001751 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752
Douglas Gregorf282a762011-01-21 19:38:21 +00001753 return Res;
1754}
1755
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001756/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +00001757///
John McCalldadc5752010-08-24 06:29:42 +00001758StmtResult
Steve Naroffc540d662008-09-03 18:15:37 +00001759Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +00001760 // If this is the first return we've seen in the block, infer the type of
1761 // the block from it.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001762 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001763 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +00001764 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +00001765 // Don't call UsualUnaryConversions(), since we don't want to do
1766 // integer promotions here.
John Wiegley01296292011-04-08 18:41:53 +00001767 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1768 if (Result.isInvalid())
1769 return StmtError();
1770 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00001771
1772 if (!RetValExp->isTypeDependent()) {
1773 CurBlock->ReturnType = RetValExp->getType();
1774 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1775 // We have to remove a 'const' added to copied-in variable which was
1776 // part of the implementation spec. and not the actual qualifier for
1777 // the variable.
1778 if (CDRE->isConstQualAdded())
1779 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1780 }
1781 } else
1782 CurBlock->ReturnType = Context.DependentTy;
Steve Naroff3b1e1722008-09-16 22:25:10 +00001783 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001784 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +00001785 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001786 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +00001787
John McCall3882ace2011-01-05 12:14:39 +00001788 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +00001789 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1790 << getCurFunctionOrMethodDecl()->getDeclName();
1791 return StmtError();
1792 }
1793
Steve Naroffc540d662008-09-03 18:15:37 +00001794 // Otherwise, verify that this result type matches the previous one. We are
1795 // pickier with blocks than for normal functions because we don't have GCC
1796 // compatibility to worry about here.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001797 ReturnStmt *Result = 0;
Steve Naroffc540d662008-09-03 18:15:37 +00001798 if (CurBlock->ReturnType->isVoidType()) {
Douglas Gregor7f139d82011-06-05 05:14:41 +00001799 if (RetValExp && !RetValExp->isTypeDependent() &&
1800 (!getLangOptions().CPlusPlus || !RetValExp->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00001801 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroffc540d662008-09-03 18:15:37 +00001802 RetValExp = 0;
1803 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001804 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1805 } else if (!RetValExp) {
Douglas Gregor7f139d82011-06-05 05:14:41 +00001806 if (!CurBlock->ReturnType->isDependentType())
1807 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1808
1809 Result = new (Context) ReturnStmt(ReturnLoc, 0, 0);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001810 } else {
1811 const VarDecl *NRVOCandidate = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001813 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1814 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001815
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001816 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1817 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1818 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001819
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001820 // In C++ the return statement is handled via a copy initialization.
1821 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001822 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001824 FnRetType,
1825 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001827 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001828 if (Res.isInvalid()) {
1829 // FIXME: Cleanup temporaries here, anyway?
1830 return StmtError();
1831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832
John McCallacf0ee52010-10-08 02:01:28 +00001833 if (RetValExp) {
1834 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001835 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001836 }
Mike Stump82f071f2009-02-04 22:31:32 +00001837
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001838 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001839 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001840 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlsson6f923f82010-01-29 18:30:20 +00001841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001843 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroffc540d662008-09-03 18:15:37 +00001844 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001845
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001847 // return statement in our scope for later processing.
Douglas Gregor0aa91e02011-06-05 05:04:23 +00001848 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001849 !CurContext->isDependentContext())
1850 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001851
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001852 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00001853}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001854
John McCalldadc5752010-08-24 06:29:42 +00001855StmtResult
John McCallb268a282010-08-23 23:25:46 +00001856Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00001857 // Check for unexpanded parameter packs.
1858 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1859 return StmtError();
1860
Douglas Gregor9a28e842010-03-01 23:15:13 +00001861 if (getCurBlock())
Steve Naroffc540d662008-09-03 18:15:37 +00001862 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001863
Chris Lattner79413952008-12-04 23:50:19 +00001864 QualType FnRetType;
Douglas Gregor33823722011-06-11 01:09:30 +00001865 QualType DeclaredRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001866 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001867 FnRetType = FD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00001868 DeclaredRetType = FnRetType;
John McCallab26cfa2010-02-05 21:31:56 +00001869 if (FD->hasAttr<NoReturnAttr>() ||
1870 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00001871 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001872 << getCurFunctionOrMethodDecl()->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00001873 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1874 DeclaredRetType = MD->getResultType();
1875 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1876 // In the implementation of a method with a related return type, the
1877 // type used to type-check the validity of return statements within the
1878 // method body is a pointer to the type of the class being implemented.
1879 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface());
1880 FnRetType = Context.getObjCObjectPointerType(FnRetType);
1881 } else {
1882 FnRetType = DeclaredRetType;
1883 }
1884 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00001885 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001886
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001887 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00001888 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00001889 if (RetValExp) {
1890 if (!RetValExp->isTypeDependent()) {
1891 // C99 6.8.6.4p1 (ext_ since GCC warns)
1892 unsigned D = diag::ext_return_has_expr;
1893 if (RetValExp->getType()->isVoidType())
1894 D = diag::ext_return_has_void_expr;
1895 else {
1896 ExprResult Result = Owned(RetValExp);
1897 Result = IgnoredValueConversions(Result.take());
1898 if (Result.isInvalid())
1899 return StmtError();
1900 RetValExp = Result.take();
1901 RetValExp = ImpCastExprToType(RetValExp,
1902 Context.VoidTy, CK_ToVoid).take();
1903 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001904
Nick Lewycky1be750a2011-06-01 07:44:31 +00001905 // return (some void expression); is legal in C++.
1906 if (D != diag::ext_return_has_void_expr ||
1907 !getLangOptions().CPlusPlus) {
1908 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00001909
1910 int FunctionKind = 0;
1911 if (isa<ObjCMethodDecl>(CurDecl))
1912 FunctionKind = 1;
1913 else if (isa<CXXConstructorDecl>(CurDecl))
1914 FunctionKind = 2;
1915 else if (isa<CXXDestructorDecl>(CurDecl))
1916 FunctionKind = 3;
1917
Nick Lewycky1be750a2011-06-01 07:44:31 +00001918 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00001919 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00001920 << RetValExp->getSourceRange();
1921 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00001922 }
Mike Stump11289f42009-09-09 15:08:12 +00001923
John McCallacf0ee52010-10-08 02:01:28 +00001924 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001925 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001928 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1929 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001930 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1931 // C99 6.8.6.4p1 (ext_ since GCC warns)
1932 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1933
1934 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001935 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001936 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001937 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001938 Result = new (Context) ReturnStmt(ReturnLoc);
1939 } else {
1940 const VarDecl *NRVOCandidate = 0;
1941 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1942 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001943
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001944 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1945 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1946 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001947
John McCallfa272342011-06-16 23:24:51 +00001948 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001949 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00001950 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001952 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00001953 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00001955 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001956 if (Res.isInvalid()) {
1957 // FIXME: Cleanup temporaries here, anyway?
1958 return StmtError();
1959 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001960
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001961 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001963 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
John McCallacf0ee52010-10-08 02:01:28 +00001966 if (RetValExp) {
Douglas Gregor33823722011-06-11 01:09:30 +00001967 // If we type-checked an Objective-C method's return type based
1968 // on a related return type, we may need to adjust the return
1969 // type again. Do so now.
1970 if (DeclaredRetType != FnRetType) {
1971 ExprResult result = PerformImplicitConversion(RetValExp,
1972 DeclaredRetType,
1973 AA_Returning);
1974 if (result.isInvalid()) return StmtError();
1975 RetValExp = result.take();
1976 }
1977
John McCallacf0ee52010-10-08 02:01:28 +00001978 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00001979 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00001980 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001981 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00001982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983
1984 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001985 // return statement in our scope for later processing.
1986 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1987 !CurContext->isDependentContext())
1988 FunctionScopes.back()->Returns.push_back(Result);
John McCall31168b02011-06-15 23:02:42 +00001989
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001990 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001991}
1992
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001993/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1994/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1995/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1996/// provide a strong guidance to not use it.
1997///
1998/// This method checks to see if the argument is an acceptable l-value and
1999/// returns false if it is a case we can handle.
2000static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00002001 // Type dependent expressions will be checked during instantiation.
2002 if (E->isTypeDependent())
2003 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
John McCall086a4642010-11-24 05:12:34 +00002005 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002006 return false; // Cool, this is an lvalue.
2007
2008 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2009 // are supposed to allow.
2010 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00002011 if (E != E2 && E2->isLValue()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002012 if (!S.getLangOptions().HeinousExtensions)
2013 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2014 << E->getSourceRange();
2015 else
2016 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2017 << E->getSourceRange();
2018 // Accept, even if we emitted an error diagnostic.
2019 return false;
2020 }
2021
2022 // None of the above, just randomly invalid non-lvalue.
2023 return true;
2024}
2025
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002026/// isOperandMentioned - Return true if the specified operand # is mentioned
2027/// anywhere in the decomposed asm string.
2028static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00002029 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002030 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2031 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2032 if (!Piece.isOperand()) continue;
2033
2034 // If this is a reference to the input and if the input was the smaller
2035 // one, then we have to reject this asm.
2036 if (Piece.getOperandNo() == OpNo)
2037 return true;
2038 }
2039
2040 return false;
2041}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002042
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002043StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2044 bool IsVolatile, unsigned NumOutputs,
2045 unsigned NumInputs, IdentifierInfo **Names,
2046 MultiExprArg constraints, MultiExprArg exprs,
2047 Expr *asmString, MultiExprArg clobbers,
2048 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002049 unsigned NumClobbers = clobbers.size();
2050 StringLiteral **Constraints =
2051 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00002052 Expr **Exprs = exprs.get();
2053 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00002054 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2055
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002056 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00002057
Chris Lattner496acc12008-08-18 19:55:17 +00002058 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002059 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002060 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2061 << AsmString->getSourceRange());
2062
Chris Lattner496acc12008-08-18 19:55:17 +00002063 for (unsigned i = 0; i != NumOutputs; i++) {
2064 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002065 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002066 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2067 << Literal->getSourceRange());
2068
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002069 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002070 if (Names[i])
2071 OutputName = Names[i]->getName();
2072
2073 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002074 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002075 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002076 diag::err_asm_invalid_output_constraint)
2077 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002078
Anders Carlssonf511f642007-11-27 04:11:28 +00002079 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002080 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002081 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002082 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002083 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002084 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Chris Lattnerd9725f72009-04-26 07:16:29 +00002087 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002088 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002089
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002090 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002091
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002092 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002093 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002094 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002095 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2096 << Literal->getSourceRange());
2097
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002098 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002099 if (Names[i])
2100 InputName = Names[i]->getName();
2101
2102 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foad7d0479f2009-05-21 09:52:38 +00002103 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002104 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002105 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002106 diag::err_asm_invalid_input_constraint)
2107 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002108 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002109
Eli Friedman47e78572009-05-03 07:49:42 +00002110 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002111
Anders Carlsson224fca82009-01-20 20:49:22 +00002112 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002113 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002114 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002115 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002116 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002117 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002118 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002119 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002120
Chris Lattnerd9725f72009-04-26 07:16:29 +00002121 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002122 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002123 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002124 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002125 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002126 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002127 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002128 }
Mike Stump11289f42009-09-09 15:08:12 +00002129
John Wiegley01296292011-04-08 18:41:53 +00002130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2131 if (Result.isInvalid())
2132 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002133
John Wiegley01296292011-04-08 18:41:53 +00002134 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002135 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002136 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002137
Anders Carlsson290aa852007-11-25 00:25:21 +00002138 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002139 for (unsigned i = 0; i != NumClobbers; i++) {
2140 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002141 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002142 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2143 << Literal->getSourceRange());
2144
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002145 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002146
Eric Christopherfd9a5f42011-06-28 18:20:53 +00002147 if (!Context.Target.isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002148 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002149 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002150 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002151
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002152 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2154 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002155 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002156 // Validate the asm string, ensuring it makes sense given the operands we
2157 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002159 unsigned DiagOffs;
2160 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002161 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2162 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002163 return StmtError();
2164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
Chris Lattner34b51e82009-05-03 05:55:43 +00002166 // Validate tied input operands for type mismatches.
2167 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2168 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002169
Chris Lattner34b51e82009-05-03 05:55:43 +00002170 // If this is a tied constraint, verify that the output and input have
2171 // either exactly the same type, or that they are int/ptr operands with the
2172 // same size (int/long, int*/long, are ok etc).
2173 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Chris Lattner34b51e82009-05-03 05:55:43 +00002175 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002176 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002177 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002178 Expr *InputExpr = Exprs[InputOpNo];
Chris Lattner2c295cf2009-05-03 05:59:17 +00002179 QualType InTy = InputExpr->getType();
2180 QualType OutTy = OutputExpr->getType();
2181 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002182 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002183
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002184 // Decide if the input and output are in the same domain (integer/ptr or
2185 // floating point.
2186 enum AsmDomain {
2187 AD_Int, AD_FP, AD_Other
2188 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002190 if (InTy->isIntegerType() || InTy->isPointerType())
2191 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002192 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002193 InputDomain = AD_FP;
2194 else
2195 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002197 if (OutTy->isIntegerType() || OutTy->isPointerType())
2198 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002199 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002200 OutputDomain = AD_FP;
2201 else
2202 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002204 // They are ok if they are the same size and in the same domain. This
2205 // allows tying things like:
2206 // void* to int*
2207 // void* to int if they are the same size.
2208 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002210 uint64_t OutSize = Context.getTypeSize(OutTy);
2211 uint64_t InSize = Context.getTypeSize(InTy);
2212 if (OutSize == InSize && InputDomain == OutputDomain &&
2213 InputDomain != AD_Other)
2214 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002215
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002216 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002217 // then we can promote the smaller one to a larger input and the asm string
2218 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002219 bool SmallerValueMentioned = false;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002220
2221 // If this is a reference to the input and if the input was the smaller
2222 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002223 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002224 // This is a use in the asm string of the smaller operand. Since we
2225 // codegen this by promoting to a wider value, the asm will get printed
2226 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002227 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002228 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002229 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002230 // If this is a reference to the output, and if the output is the larger
2231 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002232 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002235 // If the smaller value wasn't mentioned in the asm string, and if the
2236 // output was a register, just extend the shorter one to the size of the
2237 // larger one.
2238 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2239 OutputConstraintInfos[TiedTo].allowsRegister())
2240 continue;
Chris Lattnere3694b12011-02-21 21:50:25 +00002241
Chris Lattner93ede022011-02-21 22:09:29 +00002242 // Either both of the operands were mentioned or the smaller one was
2243 // mentioned. One more special case that we'll allow: if the tied input is
2244 // integer, unmentioned, and is a constant, then we'll allow truncating it
2245 // down to the size of the destination.
2246 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2247 !isOperandMentioned(InputOpNo, Pieces) &&
2248 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002249 CastKind castKind =
2250 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2251 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002252 Exprs[InputOpNo] = InputExpr;
2253 NS->setInputExpr(i, InputExpr);
2254 continue;
2255 }
2256
Chris Lattner28b05c82009-05-03 06:50:40 +00002257 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002258 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002259 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002260 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002261 return StmtError();
2262 }
Mike Stump11289f42009-09-09 15:08:12 +00002263
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002264 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002265}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002266
John McCalldadc5752010-08-24 06:29:42 +00002267StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00002268Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00002269 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00002270 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00002271 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00002272 if (Var && Var->isInvalidDecl())
2273 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274
John McCallb268a282010-08-23 23:25:46 +00002275 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002276}
2277
John McCalldadc5752010-08-24 06:29:42 +00002278StmtResult
John McCallb268a282010-08-23 23:25:46 +00002279Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2280 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00002281}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002282
John McCalldadc5752010-08-24 06:29:42 +00002283StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002284Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00002285 MultiStmtArg CatchStmts, Stmt *Finally) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002286 if (!getLangOptions().ObjCExceptions)
2287 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2288
John McCallaab3e412010-08-25 08:40:02 +00002289 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00002290 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00002291 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2292 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00002293 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00002294 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002295}
2296
John McCalldadc5752010-08-24 06:29:42 +00002297StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCallb268a282010-08-23 23:25:46 +00002298 Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00002299 if (Throw) {
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002300 Throw = MaybeCreateExprWithCleanups(Throw);
John Wiegley01296292011-04-08 18:41:53 +00002301 ExprResult Result = DefaultLvalueConversion(Throw);
2302 if (Result.isInvalid())
2303 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00002304
John Wiegley01296292011-04-08 18:41:53 +00002305 Throw = Result.take();
Douglas Gregor2900c162010-04-22 21:44:01 +00002306 QualType ThrowType = Throw->getType();
2307 // Make sure the expression type is an ObjC pointer or "void *".
2308 if (!ThrowType->isDependentType() &&
2309 !ThrowType->isObjCObjectPointerType()) {
2310 const PointerType *PT = ThrowType->getAs<PointerType>();
2311 if (!PT || !PT->getPointeeType()->isVoidType())
2312 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2313 << Throw->getType() << Throw->getSourceRange());
2314 }
2315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002316
John McCallb268a282010-08-23 23:25:46 +00002317 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00002318}
2319
John McCalldadc5752010-08-24 06:29:42 +00002320StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00002322 Scope *CurScope) {
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00002323 if (!getLangOptions().ObjCExceptions)
2324 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2325
John McCallb268a282010-08-23 23:25:46 +00002326 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00002327 // @throw without an expression designates a rethrow (which much occur
2328 // in the context of an @catch clause).
2329 Scope *AtCatchParent = CurScope;
2330 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2331 AtCatchParent = AtCatchParent->getParent();
2332 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00002333 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002334 }
Fariborz Jahanian517695b2011-07-20 23:39:56 +00002335
John McCallb268a282010-08-23 23:25:46 +00002336 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00002337}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00002338
John McCalld9bb7432011-07-27 21:50:02 +00002339ExprResult
2340Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2341 ExprResult result = DefaultLvalueConversion(operand);
2342 if (result.isInvalid())
2343 return ExprError();
2344 operand = result.take();
2345
2346 // Make sure the expression type is an ObjC pointer or "void *".
2347 QualType type = operand->getType();
2348 if (!type->isDependentType() &&
2349 !type->isObjCObjectPointerType()) {
2350 const PointerType *pointerType = type->getAs<PointerType>();
2351 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2352 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2353 << type << operand->getSourceRange();
2354 }
2355
2356 // The operand to @synchronized is a full-expression.
2357 return MaybeCreateExprWithCleanups(operand);
2358}
2359
John McCalldadc5752010-08-24 06:29:42 +00002360StmtResult
John McCallb268a282010-08-23 23:25:46 +00002361Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2362 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00002363 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00002364 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00002365 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00002366}
Sebastian Redl54c04d42008-12-22 19:15:10 +00002367
2368/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2369/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00002370StmtResult
John McCall48871652010-08-21 09:40:31 +00002371Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00002372 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00002373 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00002374 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00002375 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00002376 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00002377}
Sebastian Redl9b244a82008-12-22 21:35:02 +00002378
John McCall31168b02011-06-15 23:02:42 +00002379StmtResult
2380Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2381 getCurFunction()->setHasBranchProtectedScope();
2382 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2383}
2384
Dan Gohman28ade552010-07-26 21:25:24 +00002385namespace {
2386
Sebastian Redl63c4da02009-07-29 17:15:45 +00002387class TypeWithHandler {
2388 QualType t;
2389 CXXCatchStmt *stmt;
2390public:
2391 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2392 : t(type), stmt(statement) {}
2393
John McCall8ccfcb52009-09-24 19:53:00 +00002394 // An arbitrary order is fine as long as it places identical
2395 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00002396 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002397 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002398 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00002399 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00002400 return false;
2401 else
2402 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Sebastian Redl63c4da02009-07-29 17:15:45 +00002405 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002406 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00002407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Sebastian Redl63c4da02009-07-29 17:15:45 +00002409 CXXCatchStmt *getCatchStmt() const { return stmt; }
2410 SourceLocation getTypeSpecStartLoc() const {
2411 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2412 }
2413};
2414
Dan Gohman28ade552010-07-26 21:25:24 +00002415}
2416
Sebastian Redl9b244a82008-12-22 21:35:02 +00002417/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2418/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00002419StmtResult
John McCallb268a282010-08-23 23:25:46 +00002420Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00002421 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002422 // Don't report an error if 'try' is used in system headers.
Anders Carlssone96ab552011-02-28 02:27:16 +00002423 if (!getLangOptions().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00002424 !getSourceManager().isInSystemHeader(TryLoc))
2425 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00002426
Sebastian Redl9b244a82008-12-22 21:35:02 +00002427 unsigned NumHandlers = RawHandlers.size();
2428 assert(NumHandlers > 0 &&
2429 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00002430 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00002431
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002432 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00002433
2434 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002435 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00002436 if (!Handler->getExceptionDecl()) {
2437 if (i < NumHandlers - 1)
2438 return StmtError(Diag(Handler->getLocStart(),
2439 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00002440
Sebastian Redl63c4da02009-07-29 17:15:45 +00002441 continue;
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Sebastian Redl63c4da02009-07-29 17:15:45 +00002444 const QualType CaughtType = Handler->getCaughtType();
2445 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2446 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002447 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00002448
2449 // Detect handlers for the same type as an earlier one.
2450 if (NumHandlers > 1) {
2451 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00002452
Sebastian Redl63c4da02009-07-29 17:15:45 +00002453 TypeWithHandler prev = TypesWithHandlers[0];
2454 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2455 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00002456
Sebastian Redl63c4da02009-07-29 17:15:45 +00002457 if (curr == prev) {
2458 Diag(curr.getTypeSpecStartLoc(),
2459 diag::warn_exception_caught_by_earlier_handler)
2460 << curr.getCatchStmt()->getCaughtType().getAsString();
2461 Diag(prev.getTypeSpecStartLoc(),
2462 diag::note_previous_exception_handler)
2463 << prev.getCatchStmt()->getCaughtType().getAsString();
2464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Sebastian Redl63c4da02009-07-29 17:15:45 +00002466 prev = curr;
2467 }
2468 }
Mike Stump11289f42009-09-09 15:08:12 +00002469
John McCallaab3e412010-08-25 08:40:02 +00002470 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00002471
Sebastian Redl9b244a82008-12-22 21:35:02 +00002472 // FIXME: We should detect handlers that cannot catch anything because an
2473 // earlier handler catches a superclass. Need to find a method that is not
2474 // quadratic for this.
2475 // Neither of these are explicitly forbidden, but every compiler detects them
2476 // and warns.
2477
John McCallb268a282010-08-23 23:25:46 +00002478 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00002479 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00002480}
John Wiegley1c0675e2011-04-28 01:08:34 +00002481
2482StmtResult
2483Sema::ActOnSEHTryBlock(bool IsCXXTry,
2484 SourceLocation TryLoc,
2485 Stmt *TryBlock,
2486 Stmt *Handler) {
2487 assert(TryBlock && Handler);
2488
2489 getCurFunction()->setHasBranchProtectedScope();
2490
2491 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2492}
2493
2494StmtResult
2495Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2496 Expr *FilterExpr,
2497 Stmt *Block) {
2498 assert(FilterExpr && Block);
2499
2500 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00002501 return StmtError(Diag(FilterExpr->getExprLoc(),
2502 diag::err_filter_expression_integral)
2503 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00002504 }
2505
2506 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2507}
2508
2509StmtResult
2510Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2511 Stmt *Block) {
2512 assert(Block);
2513 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2514}