blob: cecc9b32c10dd7e90aae0276d1e760c93f066dcf [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
14#include "Sema.h"
Anders Carlsson59689ed2008-11-22 21:04:56 +000015#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000019#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
21#include "clang/AST/StmtCXX.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000022#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000023#include "clang/Basic/TargetInfo.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000026using namespace clang;
27
Anders Carlsson24824e52009-05-17 21:11:30 +000028Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
29 Expr *E = expr->takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +000030 assert(E && "ActOnExprStmt(): missing expression");
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +000031 if (E->getType()->isObjCInterfaceType()) {
32 if (LangOpts.ObjCNonFragileABI)
33 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object)
34 << E->getType();
35 else
36 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported)
37 << E->getType();
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
Sebastian Redl52f03ba2008-12-21 12:04:03 +000049Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
Ted Kremenek5a201952009-02-07 01:47:29 +000050 return Owned(new (Context) NullStmt(SemiLoc));
Chris Lattner0f203a72007-05-28 01:45:28 +000051}
52
Chris Lattner5bbb3c82009-03-29 16:50:03 +000053Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
Sebastian Redl52f03ba2008-12-21 12:04:03 +000054 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>();
66
67 // If we have an invalid decl, just return.
68 if (DG.isNull() || !DG.isSingleDecl()) return;
69 // suppress any potential 'unused variable' warning.
70 DG.getSingleDecl()->setUsed();
71}
72
Anders Carlsson59a2ab92009-07-30 22:17:18 +000073void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Anders Carlsson5c5f1602009-07-30 22:39:03 +000074 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +000075 if (!E)
76 return;
77
78 // Ignore expressions that have void type.
79 if (E->getType()->isVoidType())
80 return;
Mike Stump11289f42009-09-09 15:08:12 +000081
Anders Carlsson59a2ab92009-07-30 22:17:18 +000082 SourceLocation Loc;
83 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +000084 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +000085 return;
Mike Stump11289f42009-09-09 15:08:12 +000086
Chris Lattner2ba5ca92009-08-16 16:57:27 +000087 // Okay, we have an unused result. Depending on what the base expression is,
88 // we might want to make a more specific diagnostic. Check for one of these
89 // cases now.
90 unsigned DiagID = diag::warn_unused_expr;
91 E = E->IgnoreParens();
Fariborz Jahanian9a846652009-08-20 17:02:02 +000092 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
Chris Lattner2ba5ca92009-08-16 16:57:27 +000093 DiagID = diag::warn_unused_property_expr;
Chris Lattner1a6babf2009-10-13 04:53:48 +000094
95 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
96 // If the callee has attribute pure, const, or warn_unused_result, warn with
97 // a more specific message to make it clear what is happening.
98 if (const FunctionDecl *FD = CE->getDirectCallee()) {
99 if (FD->getAttr<WarnUnusedResultAttr>()) {
100 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
101 return;
102 }
103 if (FD->getAttr<PureAttr>()) {
104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
105 return;
106 }
107 if (FD->getAttr<ConstAttr>()) {
108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
109 return;
110 }
111 }
112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000114 Diag(Loc, DiagID) << R1 << R2;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000115}
116
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000117Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000118Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000119 MultiStmtArg elts, bool isStmtExpr) {
120 unsigned NumElts = elts.size();
121 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000122 // If we're in C89 mode, check that we don't have any decls after stmts. If
123 // so, emit an extension diagnostic.
124 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
125 // Note that __extension__ can be around a decl.
126 unsigned i = 0;
127 // Skip over all declarations.
128 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
129 /*empty*/;
130
131 // We found the end of the list or a statement. Scan for another declstmt.
132 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
133 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattnerd864daf2007-08-27 04:29:41 +0000135 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000136 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000137 Diag(D->getLocation(), diag::ext_mixed_decls_code);
138 }
139 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000140 // Warn about unused expressions in statements.
141 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000142 // Ignore statements that are last in a statement expression.
143 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000144 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000145
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000146 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000147 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000148
Ted Kremenek5a201952009-02-07 01:47:29 +0000149 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000150}
151
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000152Action::OwningStmtResult
153Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
154 SourceLocation DotDotDotLoc, ExprArg rhsval,
Chris Lattner34a22092009-03-04 04:23:07 +0000155 SourceLocation ColonLoc) {
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000156 assert((lhsval.get() != 0) && "missing expression in case statement");
157
Steve Naroff8eeeb132007-05-08 21:09:37 +0000158 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000159 // However, GCC allows any evaluatable integer expression.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000160 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
Mike Stump11289f42009-09-09 15:08:12 +0000161 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000162 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000163 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000164
Chris Lattner46eeb222007-07-18 02:28:47 +0000165 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000166
167 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000168 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
169 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000170 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000171 rhsval = 0;
172 }
173
Chris Lattner96b31392009-04-18 20:10:59 +0000174 if (getSwitchStack().empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000175 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000176 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000177 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000178
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000179 // Only now release the smart pointers.
180 lhsval.release();
181 rhsval.release();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000182 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
183 ColonLoc);
Chris Lattner96b31392009-04-18 20:10:59 +0000184 getSwitchStack().back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000185 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000186}
187
Chris Lattner34a22092009-03-04 04:23:07 +0000188/// ActOnCaseStmtBody - This installs a statement as the body of a case.
189void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
190 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000191 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Chris Lattner34a22092009-03-04 04:23:07 +0000192 CS->setSubStmt(SubStmt);
193}
194
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000195Action::OwningStmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000196Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000197 StmtArg subStmt, Scope *CurScope) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000198 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000199
Chris Lattner96b31392009-04-18 20:10:59 +0000200 if (getSwitchStack().empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000201 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000202 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000203 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000204
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000205 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Chris Lattner96b31392009-04-18 20:10:59 +0000206 getSwitchStack().back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000207 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000208}
209
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000210Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000211Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000212 SourceLocation ColonLoc, StmtArg subStmt) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000213 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Steve Naroffd123bd02009-02-28 16:48:43 +0000214 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000215 LabelStmt *&LabelDecl = getLabelMap()[II];
Steve Naroffd123bd02009-02-28 16:48:43 +0000216
Chris Lattnere2473062007-05-28 06:28:18 +0000217 // If not forward referenced or defined already, just create a new LabelStmt.
Steve Naroff846b1ec2009-03-13 15:38:40 +0000218 if (LabelDecl == 0)
219 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000220
Chris Lattnereefa10e2007-05-28 06:56:27 +0000221 assert(LabelDecl->getID() == II && "Label mismatch!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000222
Chris Lattnere2473062007-05-28 06:28:18 +0000223 // Otherwise, this label was either forward reference or multiply defined. If
224 // multiply defined, reject it now.
225 if (LabelDecl->getSubStmt()) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000226 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
Chris Lattner0369c572008-11-23 23:12:31 +0000227 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000228 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000229 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000230
Chris Lattnere2473062007-05-28 06:28:18 +0000231 // Otherwise, this label was forward declared, and we just found its real
232 // definition. Fill in the forward definition and return it.
233 LabelDecl->setIdentLoc(IdentLoc);
Chris Lattner39407372007-07-21 03:00:26 +0000234 LabelDecl->setSubStmt(SubStmt);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000235 return Owned(LabelDecl);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000236}
237
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000238Action::OwningStmtResult
Anders Carlsson52627462009-05-17 18:26:53 +0000239Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000240 StmtArg ThenVal, SourceLocation ElseLoc,
241 StmtArg ElseVal) {
Anders Carlsson52627462009-05-17 18:26:53 +0000242 OwningExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000243
Anders Carlsson52627462009-05-17 18:26:53 +0000244 Expr *condExpr = CondResult.takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +0000245 assert(condExpr && "ActOnIfStmt(): missing expression");
Douglas Gregor633caca2009-11-23 23:44:04 +0000246
247 VarDecl *ConditionVar = 0;
248 if (CXXConditionDeclExpr *Cond = dyn_cast<CXXConditionDeclExpr>(condExpr)) {
249 ConditionVar = Cond->getVarDecl();
250 condExpr = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
251 ConditionVar->getLocation(),
252 ConditionVar->getType().getNonReferenceType());
253 // FIXME: Leaks the old condExpr
254 }
255
John McCalld5707ab2009-10-12 21:59:07 +0000256 if (CheckBooleanCondition(condExpr, IfLoc)) {
Anders Carlsson52627462009-05-17 18:26:53 +0000257 CondResult = condExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000258 return StmtError();
Douglas Gregor9d73cab2009-05-15 18:53:42 +0000259 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000260
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000261 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000262 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000263
Anders Carlssondb83d772007-10-10 20:50:11 +0000264 // Warn if the if block has a null body without an else value.
265 // this helps prevent bugs due to typos, such as
266 // if (condition);
267 // do_stuff();
Mike Stump11289f42009-09-09 15:08:12 +0000268 if (!ElseVal.get()) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000269 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
270 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
271 }
272
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000273 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
274 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlsson52627462009-05-17 18:26:53 +0000276 CondResult.release();
Douglas Gregor633caca2009-11-23 23:44:04 +0000277 return Owned(new (Context) IfStmt(IfLoc, ConditionVar, condExpr, thenStmt,
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000278 ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000279}
Steve Naroff86272ea2007-05-29 02:14:17 +0000280
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000281Action::OwningStmtResult
282Sema::ActOnStartOfSwitchStmt(ExprArg cond) {
Douglas Gregord0c22e02009-11-23 13:46:08 +0000283 SwitchStmt *SS = new (Context) SwitchStmt(cond.takeAs<Expr>());
Chris Lattner96b31392009-04-18 20:10:59 +0000284 getSwitchStack().push_back(SS);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000285 return Owned(SS);
Anders Carlsson51873c22007-07-22 07:07:56 +0000286}
Chris Lattner46eeb222007-07-18 02:28:47 +0000287
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000288/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
289/// the specified width and sign. If an overflow occurs, detect it and emit
290/// the specified diagnostic.
291void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
292 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000293 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000294 unsigned DiagID) {
295 // Perform a conversion to the promoted condition type if needed.
296 if (NewWidth > Val.getBitWidth()) {
297 // If this is an extension, just do it.
298 llvm::APSInt OldVal(Val);
299 Val.extend(NewWidth);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000301 // If the input was signed and negative and the output is unsigned,
302 // warn.
303 if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
Chris Lattner29e812b2008-11-20 06:06:08 +0000304 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000306 Val.setIsSigned(NewSign);
307 } else if (NewWidth < Val.getBitWidth()) {
308 // If this is a truncation, check for overflow.
309 llvm::APSInt ConvVal(Val);
310 ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000311 ConvVal.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000312 ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000313 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000314 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000315 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000317 // Regardless of whether a diagnostic was emitted, really do the
318 // truncation.
319 Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000320 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000321 } else if (NewSign != Val.isSigned()) {
322 // Convert the sign to match the sign of the condition. This can cause
323 // overflow as well: unsigned(INTMIN)
324 llvm::APSInt OldVal(Val);
325 Val.setIsSigned(NewSign);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000327 if (Val.isNegative()) // Sign bit changes meaning.
Chris Lattner29e812b2008-11-20 06:06:08 +0000328 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000329 }
330}
331
Chris Lattner67998452007-08-23 18:29:20 +0000332namespace {
333 struct CaseCompareFunctor {
334 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
335 const llvm::APSInt &RHS) {
336 return LHS.first < RHS;
337 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000338 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
339 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
340 return LHS.first < RHS.first;
341 }
Chris Lattner67998452007-08-23 18:29:20 +0000342 bool operator()(const llvm::APSInt &LHS,
343 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
344 return LHS < RHS.first;
345 }
346 };
347}
348
Chris Lattner4b2ff022007-09-21 18:15:22 +0000349/// CmpCaseVals - Comparison predicate for sorting case values.
350///
351static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
352 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
353 if (lhs.first < rhs.first)
354 return true;
355
356 if (lhs.first == rhs.first &&
357 lhs.second->getCaseLoc().getRawEncoding()
358 < rhs.second->getCaseLoc().getRawEncoding())
359 return true;
360 return false;
361}
362
Chris Lattnera96d4272009-10-16 16:45:22 +0000363/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
364/// potentially integral-promoted expression @p expr.
365static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
366 const ImplicitCastExpr *ImplicitCast =
367 dyn_cast_or_null<ImplicitCastExpr>(expr);
368 if (ImplicitCast != NULL) {
369 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
370 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
371 if (TypeBeforePromotion->isIntegralType()) {
372 return TypeBeforePromotion;
373 }
374 }
375 return expr->getType();
376}
377
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000378Action::OwningStmtResult
379Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
380 StmtArg Body) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000381 Stmt *BodyStmt = Body.takeAs<Stmt>();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000382
Chris Lattner96b31392009-04-18 20:10:59 +0000383 SwitchStmt *SS = getSwitchStack().back();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000384 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
385
Steve Naroff42a350a2007-09-01 21:08:38 +0000386 SS->setBody(BodyStmt, SwitchLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000387 getSwitchStack().pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000388
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000389 Expr *CondExpr = SS->getCond();
Douglas Gregord0c22e02009-11-23 13:46:08 +0000390 QualType CondTypeBeforePromotion =
391 GetTypeBeforeIntegralPromotion(CondExpr);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000392 QualType CondType = CondExpr->getType();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000393
Douglas Gregord0c22e02009-11-23 13:46:08 +0000394 if (getLangOptions().CPlusPlus) {
395 // C++ 6.4.2.p2:
396 // The condition shall be of integral type, enumeration type, or of a class
397 // type for which a single conversion function to integral or enumeration
398 // type exists (12.3). If the condition is of class type, the condition is
399 // converted by calling that conversion function, and the result of the
400 // conversion is used in place of the original condition for the remainder
401 // of this section. Integral promotions are performed.
402 if (!CondExpr->isTypeDependent()) {
Douglas Gregor378e1922009-11-23 13:53:21 +0000403 // Make sure that the condition expression has a complete type,
404 // otherwise we'll never find any conversions.
405 if (RequireCompleteType(SwitchLoc, CondType,
406 PDiag(diag::err_switch_incomplete_class_type)
407 << CondExpr->getSourceRange()))
408 return StmtError();
409
Douglas Gregord0c22e02009-11-23 13:46:08 +0000410 llvm::SmallVector<CXXConversionDecl *, 4> ViableConversions;
411 llvm::SmallVector<CXXConversionDecl *, 4> ExplicitConversions;
412 if (const RecordType *RecordTy = CondType->getAs<RecordType>()) {
413 const UnresolvedSet *Conversions
414 = cast<CXXRecordDecl>(RecordTy->getDecl())
415 ->getVisibleConversionFunctions();
416 for (UnresolvedSet::iterator I = Conversions->begin(),
417 E = Conversions->end(); I != E; ++I) {
418 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(*I))
419 if (Conversion->getConversionType().getNonReferenceType()
420 ->isIntegralType()) {
421 if (Conversion->isExplicit())
422 ExplicitConversions.push_back(Conversion);
423 else
424 ViableConversions.push_back(Conversion);
425 }
426 }
427
428 switch (ViableConversions.size()) {
429 case 0:
430 if (ExplicitConversions.size() == 1) {
431 // The user probably meant to invoke the given explicit
432 // conversion; use it.
433 QualType ConvTy
434 = ExplicitConversions[0]->getConversionType()
435 .getNonReferenceType();
436 std::string TypeStr;
437 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
438
439
440 Diag(SwitchLoc, diag::err_switch_explicit_conversion)
441 << CondType << ConvTy << CondExpr->getSourceRange()
442 << CodeModificationHint::CreateInsertion(CondExpr->getLocStart(),
443 "static_cast<" + TypeStr + ">(")
444 << CodeModificationHint::CreateInsertion(
445 PP.getLocForEndOfToken(CondExpr->getLocEnd()),
446 ")");
447 Diag(ExplicitConversions[0]->getLocation(),
448 diag::note_switch_conversion)
449 << ConvTy->isEnumeralType() << ConvTy;
450
451 // If we aren't in a SFINAE context, build a call to the
452 // explicit conversion function.
453 if (!isSFINAEContext())
454 CondExpr = BuildCXXMemberCallExpr(CondExpr,
455 ExplicitConversions[0]);
456 }
457
458 // We'll complain below about a non-integral condition type.
459 break;
460
461 case 1:
462 // Apply this conversion.
463 CondExpr = BuildCXXMemberCallExpr(CondExpr, ViableConversions[0]);
464 break;
465
466 default:
467 Diag(SwitchLoc, diag::err_switch_multiple_conversions)
468 << CondType << CondExpr->getSourceRange();
469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
470 QualType ConvTy
471 = ViableConversions[I]->getConversionType()
472 .getNonReferenceType();
473 Diag(ViableConversions[I]->getLocation(),
474 diag::note_switch_conversion)
475 << ConvTy->isEnumeralType() << ConvTy;
476 }
477 return StmtError();
478 }
479 }
480 CondType = CondExpr->getType();
481
482 if (CondType->isIntegralType() || CondType->isEnumeralType()) {
483 // Integral promotions are performed.
484 UsualUnaryConversions(CondExpr);
485 }
486 }
487 } else {
488 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
489 UsualUnaryConversions(CondExpr);
490 }
491 CondType = CondExpr->getType();
492 SS->setCond(CondExpr);
493
Chris Lattnera96d4272009-10-16 16:45:22 +0000494 // C++ 6.4.2.p2:
495 // Integral promotions are performed (on the switch condition).
496 //
497 // A case value unrepresentable by the original switch condition
498 // type (before the promotion) doesn't make sense, even when it can
499 // be represented by the promoted type. Therefore we need to find
500 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000501 if (!CondExpr->isTypeDependent()) {
502 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
503 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
504 << CondType << CondExpr->getSourceRange();
505 return StmtError();
506 }
507
508 if (CondTypeBeforePromotion->isBooleanType()) {
509 // switch(bool_expr) {...} is often a programmer error, e.g.
510 // switch(n && mask) { ... } // Doh - should be "n & mask".
511 // One can always use an if statement instead of switch(bool_expr).
512 Diag(SwitchLoc, diag::warn_bool_switch_condition)
513 << CondExpr->getSourceRange();
514 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000515 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000516
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000517 // Get the bitwidth of the switched-on value before promotions. We must
518 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000519 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000520 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000521 unsigned CondWidth
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000522 = HasDependentValue? 0
Chris Lattnera96d4272009-10-16 16:45:22 +0000523 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
524 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000526 // Accumulate all of the case values in a vector so that we can sort them
527 // and detect duplicates. This vector contains the APInt for the case after
528 // it has been converted to the condition type.
Chris Lattner67998452007-08-23 18:29:20 +0000529 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
530 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000532 // Keep track of any GNU case ranges we see. The APSInt is the low value.
533 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000535 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Chris Lattner10cb5e52007-08-23 06:23:56 +0000537 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000538
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000539 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000540 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000541
Anders Carlsson51873c22007-07-22 07:07:56 +0000542 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000543 if (TheDefaultStmt) {
544 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000545 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000546
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000547 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000548 // we'll return a valid AST. This requires recursing down the AST and
549 // finding it, not something we are set up to do right now. For now,
550 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000551 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000552 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000553 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000555 } else {
556 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000557
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000558 // We already verified that the expression has a i-c-e value (C99
559 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000560 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000561
562 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
563 HasDependentValue = true;
564 break;
565 }
Mike Stump11289f42009-09-09 15:08:12 +0000566
Anders Carlsson59689ed2008-11-22 21:04:56 +0000567 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000569 // Convert the value to the same width/sign as the condition.
570 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
571 CS->getLHS()->getLocStart(),
572 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000573
Chris Lattnera65e1f32008-01-16 19:17:22 +0000574 // If the LHS is not the same type as the condition, insert an implicit
575 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000576 ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
Chris Lattnera65e1f32008-01-16 19:17:22 +0000577 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000578
Chris Lattner10cb5e52007-08-23 06:23:56 +0000579 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000580 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000581 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000582 CS->getRHS()->isValueDependent()) {
583 HasDependentValue = true;
584 break;
585 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000586 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000587 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000588 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000589 }
590 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000591
592 if (!HasDependentValue) {
593 // Sort all the scalar case values so we can easily detect duplicates.
594 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
595
596 if (!CaseVals.empty()) {
597 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
598 if (CaseVals[i].first == CaseVals[i+1].first) {
599 // If we have a duplicate, report it.
600 Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
601 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000602 Diag(CaseVals[i].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000603 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000604 // FIXME: We really want to remove the bogus case stmt from the
605 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000606 CaseListIsErroneous = true;
607 }
608 }
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000611 // Detect duplicate case ranges, which usually don't exist at all in
612 // the first place.
613 if (!CaseRanges.empty()) {
614 // Sort all the case ranges by their low value so we can easily detect
615 // overlaps between ranges.
616 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000618 // Scan the ranges, computing the high values and removing empty ranges.
619 std::vector<llvm::APSInt> HiVals;
620 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
621 CaseStmt *CR = CaseRanges[i].second;
622 Expr *Hi = CR->getRHS();
623 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000624
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000625 // Convert the value to the same width/sign as the condition.
626 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
627 CR->getRHS()->getLocStart(),
628 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000629
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000630 // If the LHS is not the same type as the condition, insert an implicit
631 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000632 ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000633 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000634
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000635 // If the low value is bigger than the high value, the case is empty.
636 if (CaseRanges[i].first > HiVal) {
637 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
638 << SourceRange(CR->getLHS()->getLocStart(),
639 CR->getRHS()->getLocEnd());
640 CaseRanges.erase(CaseRanges.begin()+i);
641 --i, --e;
642 continue;
643 }
644 HiVals.push_back(HiVal);
645 }
Mike Stump11289f42009-09-09 15:08:12 +0000646
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000647 // Rescan the ranges, looking for overlap with singleton values and other
648 // ranges. Since the range list is sorted, we only need to compare case
649 // ranges with their neighbors.
650 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
651 llvm::APSInt &CRLo = CaseRanges[i].first;
652 llvm::APSInt &CRHi = HiVals[i];
653 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000654
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000655 // Check to see whether the case range overlaps with any
656 // singleton cases.
657 CaseStmt *OverlapStmt = 0;
658 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000659
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000660 // Find the smallest value >= the lower bound. If I is in the
661 // case range, then we have overlap.
662 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
663 CaseVals.end(), CRLo,
664 CaseCompareFunctor());
665 if (I != CaseVals.end() && I->first < CRHi) {
666 OverlapVal = I->first; // Found overlap with scalar.
667 OverlapStmt = I->second;
668 }
Mike Stump11289f42009-09-09 15:08:12 +0000669
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000670 // Find the smallest value bigger than the upper bound.
671 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
672 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
673 OverlapVal = (I-1)->first; // Found overlap with scalar.
674 OverlapStmt = (I-1)->second;
675 }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000677 // Check to see if this case stmt overlaps with the subsequent
678 // case range.
679 if (i && CRLo <= HiVals[i-1]) {
680 OverlapVal = HiVals[i-1]; // Found overlap with range.
681 OverlapStmt = CaseRanges[i-1].second;
682 }
Mike Stump11289f42009-09-09 15:08:12 +0000683
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000684 if (OverlapStmt) {
685 // If we have a duplicate, report it.
686 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
687 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000688 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000689 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000690 // FIXME: We really want to remove the bogus case stmt from the
691 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000692 CaseListIsErroneous = true;
693 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000694 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000695 }
696 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000697
Mike Stump87c57ac2009-05-16 07:39:55 +0000698 // FIXME: If the case list was broken is some way, we don't have a good system
699 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000700 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000701 return StmtError();
702
703 Switch.release();
704 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000705}
706
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000707Action::OwningStmtResult
Anders Carlssonee139262009-05-17 21:22:26 +0000708Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) {
709 ExprArg CondArg(Cond.release());
710 Expr *condExpr = CondArg.takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +0000711 assert(condExpr && "ActOnWhileStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000712
John McCalld5707ab2009-10-12 21:59:07 +0000713 if (CheckBooleanCondition(condExpr, WhileLoc)) {
Anders Carlssonee139262009-05-17 21:22:26 +0000714 CondArg = condExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000715 return StmtError();
Douglas Gregor8a930c32009-05-15 21:45:53 +0000716 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000717
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000718 Stmt *bodyStmt = Body.takeAs<Stmt>();
719 DiagnoseUnusedExprResult(bodyStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000720
Anders Carlssonee139262009-05-17 21:22:26 +0000721 CondArg.release();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000722 return Owned(new (Context) WhileStmt(condExpr, bodyStmt, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000723}
724
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000725Action::OwningStmtResult
726Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000727 SourceLocation WhileLoc, SourceLocation CondLParen,
728 ExprArg Cond, SourceLocation CondRParen) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000729 Expr *condExpr = Cond.takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +0000730 assert(condExpr && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000731
John McCalld5707ab2009-10-12 21:59:07 +0000732 if (CheckBooleanCondition(condExpr, DoLoc)) {
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000733 Cond = condExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000734 return StmtError();
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000735 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000736
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000737 Stmt *bodyStmt = Body.takeAs<Stmt>();
738 DiagnoseUnusedExprResult(bodyStmt);
739
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000740 Cond.release();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000741 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
Chris Lattner815b70e2009-06-12 23:04:47 +0000742 WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000743}
744
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000745Action::OwningStmtResult
746Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
747 StmtArg first, ExprArg second, ExprArg third,
748 SourceLocation RParenLoc, StmtArg body) {
749 Stmt *First = static_cast<Stmt*>(first.get());
John McCalld5707ab2009-10-12 21:59:07 +0000750 Expr *Second = second.takeAs<Expr>();
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000751 Expr *Third = static_cast<Expr*>(third.get());
752 Stmt *Body = static_cast<Stmt*>(body.get());
753
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000754 if (!getLangOptions().CPlusPlus) {
755 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000756 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
757 // declare identifiers for objects having storage class 'auto' or
758 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000759 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
760 DI!=DE; ++DI) {
761 VarDecl *VD = dyn_cast<VarDecl>(*DI);
762 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
763 VD = 0;
764 if (VD == 0)
765 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
766 // FIXME: mark decl erroneous!
767 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000768 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000769 }
John McCalld5707ab2009-10-12 21:59:07 +0000770 if (Second && CheckBooleanCondition(Second, ForLoc)) {
771 second = Second;
772 return StmtError();
Steve Naroff86272ea2007-05-29 02:14:17 +0000773 }
Mike Stump11289f42009-09-09 15:08:12 +0000774
Anders Carlsson1682af52009-08-01 01:39:59 +0000775 DiagnoseUnusedExprResult(First);
776 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000777 DiagnoseUnusedExprResult(Body);
778
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000779 first.release();
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000780 third.release();
781 body.release();
Douglas Gregor5d138682009-05-15 22:12:32 +0000782 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc,
783 LParenLoc, RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000784}
785
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000786Action::OwningStmtResult
787Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
788 SourceLocation LParenLoc,
789 StmtArg first, ExprArg second,
790 SourceLocation RParenLoc, StmtArg body) {
791 Stmt *First = static_cast<Stmt*>(first.get());
792 Expr *Second = static_cast<Expr*>(second.get());
793 Stmt *Body = static_cast<Stmt*>(body.get());
Fariborz Jahanian93977672008-01-10 20:33:58 +0000794 if (First) {
795 QualType FirstType;
796 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +0000797 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000798 return StmtError(Diag((*DS->decl_begin())->getLocation(),
799 diag::err_toomany_element_decls));
800
Chris Lattner529efc72009-03-28 06:33:19 +0000801 Decl *D = DS->getSingleDecl();
Ted Kremenek11b00422008-10-06 20:58:11 +0000802 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +0000803 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
804 // declare identifiers for objects having storage class 'auto' or
805 // 'register'.
Steve Naroff08899ff2008-04-15 22:42:06 +0000806 VarDecl *VD = cast<VarDecl>(D);
807 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000808 return StmtError(Diag(VD->getLocation(),
809 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000810 } else {
Chris Lattnercda4d7e2009-03-13 17:38:01 +0000811 if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000812 return StmtError(Diag(First->getLocStart(),
813 diag::err_selector_element_not_lvalue)
814 << First->getSourceRange());
815
Mike Stump11289f42009-09-09 15:08:12 +0000816 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818 if (!FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +0000819 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000820 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000821 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000822 }
823 if (Second) {
824 DefaultFunctionArrayConversion(Second);
825 QualType SecondType = Second->getType();
Steve Naroff79d12152009-07-16 15:41:00 +0000826 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000827 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000828 << SecondType << Second->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000829 }
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000830 first.release();
831 second.release();
832 body.release();
Ted Kremenek5a201952009-02-07 01:47:29 +0000833 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
834 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000835}
Chris Lattneraf8d5812006-11-10 05:07:45 +0000836
Sebastian Redl573feed2009-01-18 13:19:59 +0000837Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000838Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
Chris Lattneraf8d5812006-11-10 05:07:45 +0000839 IdentifierInfo *LabelII) {
Steve Naroffc540d662008-09-03 18:15:37 +0000840 // If we are in a block, reject all gotos for now.
841 if (CurBlock)
Sebastian Redl573feed2009-01-18 13:19:59 +0000842 return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
Steve Naroffc540d662008-09-03 18:15:37 +0000843
Chris Lattnere2473062007-05-28 06:28:18 +0000844 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000845 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Chris Lattnere2473062007-05-28 06:28:18 +0000846
Steve Naroff846b1ec2009-03-13 15:38:40 +0000847 // If we haven't seen this label yet, create a forward reference.
848 if (LabelDecl == 0)
Ted Kremenek5a201952009-02-07 01:47:29 +0000849 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
Sebastian Redl573feed2009-01-18 13:19:59 +0000850
Ted Kremenek5a201952009-02-07 01:47:29 +0000851 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000852}
Chris Lattner1c310502007-05-31 06:00:00 +0000853
Sebastian Redl573feed2009-01-18 13:19:59 +0000854Action::OwningStmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +0000855Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
Sebastian Redl573feed2009-01-18 13:19:59 +0000856 ExprArg DestExp) {
Eli Friedman8d7ff402009-03-26 00:18:06 +0000857 // Convert operand to void*
Eli Friedman6568eef2009-03-26 07:32:37 +0000858 Expr* E = DestExp.takeAs<Expr>();
Douglas Gregor30776d42009-05-16 00:20:29 +0000859 if (!E->isTypeDependent()) {
860 QualType ETy = E->getType();
861 AssignConvertType ConvTy =
862 CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
863 if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
864 E, "passing"))
865 return StmtError();
866 }
867 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000868}
869
Sebastian Redl573feed2009-01-18 13:19:59 +0000870Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000871Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +0000872 Scope *S = CurScope->getContinueParent();
873 if (!S) {
874 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +0000875 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +0000876 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000877
Ted Kremenek5a201952009-02-07 01:47:29 +0000878 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000879}
880
Sebastian Redl573feed2009-01-18 13:19:59 +0000881Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000882Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +0000883 Scope *S = CurScope->getBreakParent();
884 if (!S) {
885 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +0000886 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +0000887 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000888
Ted Kremenek5a201952009-02-07 01:47:29 +0000889 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000890}
891
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000892/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +0000893///
Sebastian Redl573feed2009-01-18 13:19:59 +0000894Action::OwningStmtResult
Steve Naroffc540d662008-09-03 18:15:37 +0000895Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +0000896 // If this is the first return we've seen in the block, infer the type of
897 // the block from it.
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000898 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +0000899 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +0000900 // Don't call UsualUnaryConversions(), since we don't want to do
901 // integer promotions here.
902 DefaultFunctionArrayConversion(RetValExp);
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000903 CurBlock->ReturnType = RetValExp->getType();
904 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
905 // We have to remove a 'const' added to copied-in variable which was
906 // part of the implementation spec. and not the actual qualifier for
907 // the variable.
908 if (CDRE->isConstQualAdded())
909 CurBlock->ReturnType.removeConst();
910 }
Steve Naroff3b1e1722008-09-16 22:25:10 +0000911 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000912 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +0000913 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +0000914 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +0000915
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000916 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +0000917 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
918 << getCurFunctionOrMethodDecl()->getDeclName();
919 return StmtError();
920 }
921
Steve Naroffc540d662008-09-03 18:15:37 +0000922 // Otherwise, verify that this result type matches the previous one. We are
923 // pickier with blocks than for normal functions because we don't have GCC
924 // compatibility to worry about here.
925 if (CurBlock->ReturnType->isVoidType()) {
926 if (RetValExp) {
927 Diag(ReturnLoc, diag::err_return_block_has_expr);
Ted Kremenek5a201952009-02-07 01:47:29 +0000928 RetValExp->Destroy(Context);
Steve Naroffc540d662008-09-03 18:15:37 +0000929 RetValExp = 0;
930 }
Ted Kremenek5a201952009-02-07 01:47:29 +0000931 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroffc540d662008-09-03 18:15:37 +0000932 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000933
934 if (!RetValExp)
935 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
936
Mike Stump82f071f2009-02-04 22:31:32 +0000937 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
938 // we have a non-void block with an expression, continue checking
939 QualType RetValType = RetValExp->getType();
Sebastian Redl573feed2009-01-18 13:19:59 +0000940
Mike Stump11289f42009-09-09 15:08:12 +0000941 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
942 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
Mike Stump82f071f2009-02-04 22:31:32 +0000943 // function return.
944
945 // In C++ the return statement is handled via a copy initialization.
946 // the C version of which boils down to CheckSingleAssignmentConstraints.
947 // FIXME: Leaks RetValExp.
948 if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
949 return StmtError();
950
951 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +0000952 }
Sebastian Redl573feed2009-01-18 13:19:59 +0000953
Ted Kremenek5a201952009-02-07 01:47:29 +0000954 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroffc540d662008-09-03 18:15:37 +0000955}
Chris Lattneraf8d5812006-11-10 05:07:45 +0000956
Sebastian Redl42e92c42009-04-12 17:16:29 +0000957/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
958/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
959static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
960 Expr *RetExpr) {
961 QualType ExprType = RetExpr->getType();
962 // - in a return statement in a function with ...
963 // ... a class return type ...
964 if (!RetType->isRecordType())
965 return false;
966 // ... the same cv-unqualified type as the function return type ...
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000967 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
Sebastian Redl42e92c42009-04-12 17:16:29 +0000968 return false;
969 // ... the expression is the name of a non-volatile automatic object ...
970 // We ignore parentheses here.
971 // FIXME: Is this compliant?
972 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
973 if (!DR)
974 return false;
975 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
976 if (!VD)
977 return false;
978 return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
979 && !VD->getType().isVolatileQualified();
980}
981
Sebastian Redl573feed2009-01-18 13:19:59 +0000982Action::OwningStmtResult
Anders Carlssona1929472009-08-18 16:11:00 +0000983Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
984 Expr *RetValExp = rex.takeAs<Expr>();
Steve Naroffc540d662008-09-03 18:15:37 +0000985 if (CurBlock)
986 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +0000987
Chris Lattner79413952008-12-04 23:50:19 +0000988 QualType FnRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +0000989 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +0000990 FnRetType = FD->getResultType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000991 if (FD->hasAttr<NoReturnAttr>())
Chris Lattner6e127a62009-05-31 19:32:13 +0000992 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +0000993 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpd00bc1a2009-04-29 00:43:21 +0000994 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Narofff3833d72009-03-03 00:45:38 +0000995 FnRetType = MD->getResultType();
996 else // If we don't have a function/method context, bail.
997 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +0000998
Chris Lattner9bad62c2008-01-04 18:04:52 +0000999 if (FnRetType->isVoidType()) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001000 if (RetValExp && !RetValExp->isTypeDependent()) {
1001 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner27e5bef2008-12-18 02:01:17 +00001002 unsigned D = diag::ext_return_has_expr;
1003 if (RetValExp->getType()->isVoidType())
1004 D = diag::ext_return_has_void_expr;
Sebastian Redl573feed2009-01-18 13:19:59 +00001005
Chris Lattner0cb00d62008-12-18 02:03:48 +00001006 // return (some void expression); is legal in C++.
1007 if (D != diag::ext_return_has_void_expr ||
1008 !getLangOptions().CPlusPlus) {
1009 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1010 Diag(ReturnLoc, D)
1011 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1012 << RetValExp->getSourceRange();
1013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Anders Carlssona1929472009-08-18 16:11:00 +00001015 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001016 }
Ted Kremenek5a201952009-02-07 01:47:29 +00001017 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroff9358c712007-05-27 23:58:33 +00001018 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001019
Anders Carlsson19b8c4c2009-05-15 00:48:27 +00001020 if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001021 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1022 // C99 6.8.6.4p1 (ext_ since GCC warns)
1023 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1024
1025 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001026 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001027 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001028 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Ted Kremenek5a201952009-02-07 01:47:29 +00001029 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001030 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001031
Douglas Gregor4619e432008-12-05 23:32:09 +00001032 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1033 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001034
Mike Stump11289f42009-09-09 15:08:12 +00001035 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1036 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
Sebastian Redl573feed2009-01-18 13:19:59 +00001037 // function return.
1038
Sebastian Redl42e92c42009-04-12 17:16:29 +00001039 // C++0x 12.8p15: When certain criteria are met, an implementation is
1040 // allowed to omit the copy construction of a class object, [...]
1041 // - in a return statement in a function with a class return type, when
1042 // the expression is the name of a non-volatile automatic object with
1043 // the same cv-unqualified type as the function return type, the copy
1044 // operation can be omitted [...]
1045 // C++0x 12.8p16: When the criteria for elision of a copy operation are met
1046 // and the object to be copied is designated by an lvalue, overload
1047 // resolution to select the constructor for the copy is first performed
1048 // as if the object were designated by an rvalue.
1049 // Note that we only compute Elidable if we're in C++0x, since we don't
1050 // care otherwise.
1051 bool Elidable = getLangOptions().CPlusPlus0x ?
1052 IsReturnCopyElidable(Context, FnRetType, RetValExp) :
1053 false;
1054
Douglas Gregor4619e432008-12-05 23:32:09 +00001055 // In C++ the return statement is handled via a copy initialization.
Sebastian Redl573feed2009-01-18 13:19:59 +00001056 // the C version of which boils down to CheckSingleAssignmentConstraints.
Sebastian Redl42e92c42009-04-12 17:16:29 +00001057 // FIXME: Leaks RetValExp on error.
Douglas Gregorffe14e32009-11-14 01:20:54 +00001058 if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable)){
1059 // We should still clean up our temporaries, even when we're failing!
1060 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Sebastian Redl573feed2009-01-18 13:19:59 +00001061 return StmtError();
Douglas Gregorffe14e32009-11-14 01:20:54 +00001062 }
1063
Douglas Gregor4619e432008-12-05 23:32:09 +00001064 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1065 }
1066
Anders Carlssona1929472009-08-18 16:11:00 +00001067 if (RetValExp)
1068 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Ted Kremenek5a201952009-02-07 01:47:29 +00001069 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001070}
1071
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001072/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1073/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1074/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1075/// provide a strong guidance to not use it.
1076///
1077/// This method checks to see if the argument is an acceptable l-value and
1078/// returns false if it is a case we can handle.
1079static bool CheckAsmLValue(const Expr *E, Sema &S) {
1080 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1081 return false; // Cool, this is an lvalue.
1082
1083 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1084 // are supposed to allow.
1085 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1086 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1087 if (!S.getLangOptions().HeinousExtensions)
1088 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1089 << E->getSourceRange();
1090 else
1091 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1092 << E->getSourceRange();
1093 // Accept, even if we emitted an error diagnostic.
1094 return false;
1095 }
1096
1097 // None of the above, just randomly invalid non-lvalue.
1098 return true;
1099}
1100
1101
Sebastian Redl24b8e152009-01-18 16:53:17 +00001102Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1103 bool IsSimple,
1104 bool IsVolatile,
1105 unsigned NumOutputs,
1106 unsigned NumInputs,
1107 std::string *Names,
1108 MultiExprArg constraints,
1109 MultiExprArg exprs,
1110 ExprArg asmString,
1111 MultiExprArg clobbers,
1112 SourceLocation RParenLoc) {
1113 unsigned NumClobbers = clobbers.size();
1114 StringLiteral **Constraints =
1115 reinterpret_cast<StringLiteral**>(constraints.get());
1116 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1117 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1118 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1119
Anders Carlsson570c3572009-01-27 20:38:24 +00001120 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattner496acc12008-08-18 19:55:17 +00001122 // The parser verifies that there is a string literal here.
Chris Lattner07096892008-07-23 06:46:56 +00001123 if (AsmString->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001124 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1125 << AsmString->getSourceRange());
1126
Chris Lattner496acc12008-08-18 19:55:17 +00001127 for (unsigned i = 0; i != NumOutputs; i++) {
1128 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001129 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001130 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1131 << Literal->getSourceRange());
1132
Mike Stump11289f42009-09-09 15:08:12 +00001133 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001134 Literal->getByteLength(),
1135 Names[i]);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001136 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001137 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001138 diag::err_asm_invalid_output_constraint)
1139 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001140
Anders Carlssonf511f642007-11-27 04:11:28 +00001141 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00001142 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001143 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00001144 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001145 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00001146 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Chris Lattnerd9725f72009-04-26 07:16:29 +00001149 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001150 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001151
Chris Lattner34b51e82009-05-03 05:55:43 +00001152 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1153
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001154 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00001155 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001156 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001157 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1158 << Literal->getSourceRange());
1159
Mike Stump11289f42009-09-09 15:08:12 +00001160 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001161 Literal->getByteLength(),
1162 Names[i]);
Jay Foad7d0479f2009-05-21 09:52:38 +00001163 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001164 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001165 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001166 diag::err_asm_invalid_input_constraint)
1167 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00001168 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001169
Eli Friedman47e78572009-05-03 07:49:42 +00001170 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00001171
Anders Carlsson224fca82009-01-20 20:49:22 +00001172 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00001173 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001174 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00001175 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001176 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001177 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001178 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001179 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001180
Chris Lattnerd9725f72009-04-26 07:16:29 +00001181 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00001182 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00001183 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001184 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00001185 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001186 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00001187 }
Anders Carlsson224fca82009-01-20 20:49:22 +00001188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Anders Carlssonb8482c52009-02-22 02:11:23 +00001190 DefaultFunctionArrayConversion(Exprs[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattner34b51e82009-05-03 05:55:43 +00001192 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001193 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001194
Anders Carlsson290aa852007-11-25 00:25:21 +00001195 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00001196 for (unsigned i = 0; i != NumClobbers; i++) {
1197 StringLiteral *Literal = Clobbers[i];
Chris Lattner07096892008-07-23 06:46:56 +00001198 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001199 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1200 << Literal->getSourceRange());
1201
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001202 std::string Clobber(Literal->getStrData(),
1203 Literal->getStrData() +
1204 Literal->getByteLength());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001205
Chris Lattner07096892008-07-23 06:46:56 +00001206 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001207 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001208 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00001209 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001210
1211 constraints.release();
1212 exprs.release();
1213 asmString.release();
1214 clobbers.release();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001215 AsmStmt *NS =
1216 new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1217 Names, Constraints, Exprs, AsmString, NumClobbers,
1218 Clobbers, RParenLoc);
1219 // Validate the asm string, ensuring it makes sense given the operands we
1220 // have.
1221 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1222 unsigned DiagOffs;
1223 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00001224 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1225 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001226 DeleteStmt(NS);
1227 return StmtError();
1228 }
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattner34b51e82009-05-03 05:55:43 +00001230 // Validate tied input operands for type mismatches.
1231 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1232 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattner34b51e82009-05-03 05:55:43 +00001234 // If this is a tied constraint, verify that the output and input have
1235 // either exactly the same type, or that they are int/ptr operands with the
1236 // same size (int/long, int*/long, are ok etc).
1237 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001238
Chris Lattner34b51e82009-05-03 05:55:43 +00001239 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnercb66c732009-05-03 07:04:21 +00001240 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner28b05c82009-05-03 06:50:40 +00001241 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner2c295cf2009-05-03 05:59:17 +00001242 QualType InTy = InputExpr->getType();
1243 QualType OutTy = OutputExpr->getType();
1244 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00001245 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattner2c295cf2009-05-03 05:59:17 +00001247 // Int/ptr operands have some special cases that we allow.
1248 if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1249 (InTy->isIntegerType() || InTy->isPointerType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001250
Chris Lattner2c295cf2009-05-03 05:59:17 +00001251 // They are ok if they are the same size. Tying void* to int is ok if
1252 // they are the same size, for example. This also allows tying void* to
1253 // int*.
Chris Lattnercc1cde92009-05-03 08:32:32 +00001254 uint64_t OutSize = Context.getTypeSize(OutTy);
1255 uint64_t InSize = Context.getTypeSize(InTy);
1256 if (OutSize == InSize)
Chris Lattner34b51e82009-05-03 05:55:43 +00001257 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattnercc1cde92009-05-03 08:32:32 +00001259 // If the smaller input/output operand is not mentioned in the asm string,
1260 // then we can promote it and the asm string won't notice. Check this
Chris Lattnercb66c732009-05-03 07:04:21 +00001261 // case now.
Chris Lattnercc1cde92009-05-03 08:32:32 +00001262 bool SmallerValueMentioned = false;
Chris Lattner97de21f2009-05-03 08:24:16 +00001263 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1264 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1265 if (!Piece.isOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001266
Chris Lattnercc1cde92009-05-03 08:32:32 +00001267 // If this is a reference to the input and if the input was the smaller
1268 // one, then we have to reject this asm.
1269 if (Piece.getOperandNo() == i+NumOutputs) {
1270 if (InSize < OutSize) {
1271 SmallerValueMentioned = true;
1272 break;
1273 }
1274 }
1275
1276 // If this is a reference to the input and if the input was the smaller
1277 // one, then we have to reject this asm.
1278 if (Piece.getOperandNo() == TiedTo) {
1279 if (InSize > OutSize) {
1280 SmallerValueMentioned = true;
1281 break;
1282 }
1283 }
Chris Lattnercb66c732009-05-03 07:04:21 +00001284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattnercc1cde92009-05-03 08:32:32 +00001286 // If the smaller value wasn't mentioned in the asm string, and if the
1287 // output was a register, just extend the shorter one to the size of the
1288 // larger one.
1289 if (!SmallerValueMentioned &&
Chris Lattnercb66c732009-05-03 07:04:21 +00001290 OutputConstraintInfos[TiedTo].allowsRegister())
1291 continue;
Chris Lattner34b51e82009-05-03 05:55:43 +00001292 }
Mike Stump11289f42009-09-09 15:08:12 +00001293
Chris Lattner28b05c82009-05-03 06:50:40 +00001294 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00001295 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00001296 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00001297 << InputExpr->getSourceRange();
1298 DeleteStmt(NS);
1299 return StmtError();
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001302 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00001303}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001304
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001305Action::OwningStmtResult
1306Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001307 SourceLocation RParen, DeclPtrTy Parm,
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001308 StmtArg Body, StmtArg catchList) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001309 Stmt *CatchList = catchList.takeAs<Stmt>();
Chris Lattner83f095c2009-03-28 19:18:32 +00001310 ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001311
Steve Naroff39d6fba2009-03-03 20:59:06 +00001312 // PVD == 0 implies @catch(...).
Steve Naroff27ed6f62009-03-03 21:16:54 +00001313 if (PVD) {
Chris Lattnera2ca03a2009-04-12 23:26:56 +00001314 // If we already know the decl is invalid, reject it.
1315 if (PVD->isInvalidDecl())
1316 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001317
Steve Naroff79d12152009-07-16 15:41:00 +00001318 if (!PVD->getType()->isObjCObjectPointerType())
Mike Stump11289f42009-09-09 15:08:12 +00001319 return StmtError(Diag(PVD->getLocation(),
Steve Naroff27ed6f62009-03-03 21:16:54 +00001320 diag::err_catch_param_not_objc_type));
1321 if (PVD->getType()->isObjCQualifiedIdType())
Mike Stump11289f42009-09-09 15:08:12 +00001322 return StmtError(Diag(PVD->getLocation(),
Steve Naroff013813d2009-03-03 23:13:51 +00001323 diag::err_illegal_qualifiers_on_catch_parm));
Steve Naroff27ed6f62009-03-03 21:16:54 +00001324 }
Chris Lattnera2ca03a2009-04-12 23:26:56 +00001325
Ted Kremenek5a201952009-02-07 01:47:29 +00001326 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001327 PVD, Body.takeAs<Stmt>(), CatchList);
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001328 return Owned(CatchList ? CatchList : CS);
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001329}
1330
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001331Action::OwningStmtResult
1332Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001333 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1334 static_cast<Stmt*>(Body.release())));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00001335}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001336
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001337Action::OwningStmtResult
1338Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1339 StmtArg Try, StmtArg Catch, StmtArg Finally) {
Chris Lattner9fecd742009-04-19 05:21:20 +00001340 CurFunctionNeedsScopeChecking = true;
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001341 return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1342 Catch.takeAs<Stmt>(),
1343 Finally.takeAs<Stmt>()));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001344}
1345
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001346Action::OwningStmtResult
Steve Naroff0fa412c2009-02-12 15:54:59 +00001347Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001348 Expr *ThrowExpr = expr.takeAs<Expr>();
Steve Naroffd5581d22009-02-11 17:45:08 +00001349 if (!ThrowExpr) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00001350 // @throw without an expression designates a rethrow (which much occur
1351 // in the context of an @catch clause).
1352 Scope *AtCatchParent = CurScope;
1353 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1354 AtCatchParent = AtCatchParent->getParent();
1355 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00001356 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
Steve Naroffd5581d22009-02-11 17:45:08 +00001357 } else {
1358 QualType ThrowType = ThrowExpr->getType();
1359 // Make sure the expression type is an ObjC pointer or "void *".
Steve Naroff79d12152009-07-16 15:41:00 +00001360 if (!ThrowType->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001361 const PointerType *PT = ThrowType->getAs<PointerType>();
Steve Naroffd5581d22009-02-11 17:45:08 +00001362 if (!PT || !PT->getPointeeType()->isVoidType())
Steve Naroffc49b22a2009-02-12 18:09:32 +00001363 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1364 << ThrowExpr->getType() << ThrowExpr->getSourceRange());
Steve Naroffd5581d22009-02-11 17:45:08 +00001365 }
1366 }
1367 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00001368}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001369
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001370Action::OwningStmtResult
1371Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1372 StmtArg SynchBody) {
Chris Lattnerc70dd562009-04-21 06:01:00 +00001373 CurFunctionNeedsScopeChecking = true;
1374
Chris Lattner3501d432009-04-21 06:11:25 +00001375 // Make sure the expression type is an ObjC pointer or "void *".
1376 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
Steve Naroff79d12152009-07-16 15:41:00 +00001377 if (!SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001378 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattner3501d432009-04-21 06:11:25 +00001379 if (!PT || !PT->getPointeeType()->isVoidType())
1380 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1381 << SyncExpr->getType() << SyncExpr->getSourceRange());
1382 }
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001385 SynchExpr.takeAs<Stmt>(),
1386 SynchBody.takeAs<Stmt>()));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00001387}
Sebastian Redl54c04d42008-12-22 19:15:10 +00001388
1389/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1390/// and creates a proper catch handler from them.
1391Action::OwningStmtResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001392Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
Sebastian Redl54c04d42008-12-22 19:15:10 +00001393 StmtArg HandlerBlock) {
1394 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00001395 return Owned(new (Context) CXXCatchStmt(CatchLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001396 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001397 HandlerBlock.takeAs<Stmt>()));
Sebastian Redl54c04d42008-12-22 19:15:10 +00001398}
Sebastian Redl9b244a82008-12-22 21:35:02 +00001399
Sebastian Redl63c4da02009-07-29 17:15:45 +00001400class TypeWithHandler {
1401 QualType t;
1402 CXXCatchStmt *stmt;
1403public:
1404 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1405 : t(type), stmt(statement) {}
1406
John McCall8ccfcb52009-09-24 19:53:00 +00001407 // An arbitrary order is fine as long as it places identical
1408 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00001409 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001410 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001411 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00001412 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001413 return false;
1414 else
1415 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Sebastian Redl63c4da02009-07-29 17:15:45 +00001418 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001419 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00001420 }
Mike Stump11289f42009-09-09 15:08:12 +00001421
Sebastian Redl63c4da02009-07-29 17:15:45 +00001422 QualType getQualType() const { return t; }
1423 CXXCatchStmt *getCatchStmt() const { return stmt; }
1424 SourceLocation getTypeSpecStartLoc() const {
1425 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1426 }
1427};
1428
Sebastian Redl9b244a82008-12-22 21:35:02 +00001429/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1430/// handlers and creates a try statement from them.
1431Action::OwningStmtResult
1432Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1433 MultiStmtArg RawHandlers) {
1434 unsigned NumHandlers = RawHandlers.size();
1435 assert(NumHandlers > 0 &&
1436 "The parser shouldn't call this if there are no handlers.");
1437 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1438
Sebastian Redl63c4da02009-07-29 17:15:45 +00001439 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00001440
1441 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl9b244a82008-12-22 21:35:02 +00001442 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00001443 if (!Handler->getExceptionDecl()) {
1444 if (i < NumHandlers - 1)
1445 return StmtError(Diag(Handler->getLocStart(),
1446 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00001447
Sebastian Redl63c4da02009-07-29 17:15:45 +00001448 continue;
1449 }
Mike Stump11289f42009-09-09 15:08:12 +00001450
Sebastian Redl63c4da02009-07-29 17:15:45 +00001451 const QualType CaughtType = Handler->getCaughtType();
1452 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1453 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001454 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00001455
1456 // Detect handlers for the same type as an earlier one.
1457 if (NumHandlers > 1) {
1458 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00001459
Sebastian Redl63c4da02009-07-29 17:15:45 +00001460 TypeWithHandler prev = TypesWithHandlers[0];
1461 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1462 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00001463
Sebastian Redl63c4da02009-07-29 17:15:45 +00001464 if (curr == prev) {
1465 Diag(curr.getTypeSpecStartLoc(),
1466 diag::warn_exception_caught_by_earlier_handler)
1467 << curr.getCatchStmt()->getCaughtType().getAsString();
1468 Diag(prev.getTypeSpecStartLoc(),
1469 diag::note_previous_exception_handler)
1470 << prev.getCatchStmt()->getCaughtType().getAsString();
1471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Sebastian Redl63c4da02009-07-29 17:15:45 +00001473 prev = curr;
1474 }
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Sebastian Redl9b244a82008-12-22 21:35:02 +00001477 // FIXME: We should detect handlers that cannot catch anything because an
1478 // earlier handler catches a superclass. Need to find a method that is not
1479 // quadratic for this.
1480 // Neither of these are explicitly forbidden, but every compiler detects them
1481 // and warns.
1482
Sebastian Redl4de47b42009-04-27 20:27:31 +00001483 CurFunctionNeedsScopeChecking = true;
Sebastian Redl9b244a82008-12-22 21:35:02 +00001484 RawHandlers.release();
Ted Kremenek5a201952009-02-07 01:47:29 +00001485 return Owned(new (Context) CXXTryStmt(TryLoc,
1486 static_cast<Stmt*>(TryBlock.release()),
1487 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001488}