blob: 5392da098f95a356e08b6aed1d3ff43883fc572f [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
Anders Carlsson59689ed2008-11-22 21:04:56 +000016#include "clang/AST/APValue.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000020#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
22#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000024#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000025#include "clang/Basic/TargetInfo.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000026#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVector.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000028using namespace clang;
29
Anders Carlsson24824e52009-05-17 21:11:30 +000030Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
31 Expr *E = expr->takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +000032 assert(E && "ActOnExprStmt(): missing expression");
Chris Lattner903eb512008-07-25 23:18:17 +000033 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
34 // void expression for its side effects. Conversion to void allows any
35 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000036
Chris Lattner903eb512008-07-25 23:18:17 +000037 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000038 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000039}
40
41
Sebastian Redl52f03ba2008-12-21 12:04:03 +000042Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
Ted Kremenek5a201952009-02-07 01:47:29 +000043 return Owned(new (Context) NullStmt(SemiLoc));
Chris Lattner0f203a72007-05-28 01:45:28 +000044}
45
Chris Lattner5bbb3c82009-03-29 16:50:03 +000046Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
Sebastian Redl52f03ba2008-12-21 12:04:03 +000047 SourceLocation StartLoc,
48 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000049 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattnercbafe8d2009-04-12 20:13:14 +000051 // If we have an invalid decl, just return an error.
52 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000053
Chris Lattner34a22092009-03-04 04:23:07 +000054 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000055}
Chris Lattneraf8d5812006-11-10 05:07:45 +000056
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000057void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
58 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
59
60 // If we have an invalid decl, just return.
61 if (DG.isNull() || !DG.isSingleDecl()) return;
62 // suppress any potential 'unused variable' warning.
63 DG.getSingleDecl()->setUsed();
64}
65
Anders Carlsson59a2ab92009-07-30 22:17:18 +000066void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Anders Carlsson5c5f1602009-07-30 22:39:03 +000067 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +000068 if (!E)
69 return;
70
Anders Carlsson59a2ab92009-07-30 22:17:18 +000071 SourceLocation Loc;
72 SourceRange R1, R2;
Mike Stump53f9ded2009-11-03 23:25:48 +000073 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +000074 return;
Mike Stump11289f42009-09-09 15:08:12 +000075
Chris Lattner2ba5ca92009-08-16 16:57:27 +000076 // Okay, we have an unused result. Depending on what the base expression is,
77 // we might want to make a more specific diagnostic. Check for one of these
78 // cases now.
79 unsigned DiagID = diag::warn_unused_expr;
80 E = E->IgnoreParens();
Fariborz Jahanian9a846652009-08-20 17:02:02 +000081 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
Chris Lattner2ba5ca92009-08-16 16:57:27 +000082 DiagID = diag::warn_unused_property_expr;
Chris Lattner1a6babf2009-10-13 04:53:48 +000083
Douglas Gregor50dc2192010-02-11 22:55:30 +000084 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
85 E = Temps->getSubExpr();
Douglas Gregor50dc2192010-02-11 22:55:30 +000086
Chris Lattner1a6babf2009-10-13 04:53:48 +000087 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +000088 if (E->getType()->isVoidType())
89 return;
90
Chris Lattner1a6babf2009-10-13 04:53:48 +000091 // If the callee has attribute pure, const, or warn_unused_result, warn with
92 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +000093 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +000094 if (FD->getAttr<WarnUnusedResultAttr>()) {
95 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
96 return;
97 }
98 if (FD->getAttr<PureAttr>()) {
99 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
100 return;
101 }
102 if (FD->getAttr<ConstAttr>()) {
103 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
104 return;
105 }
106 }
107 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000108 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
109 const ObjCMethodDecl *MD = ME->getMethodDecl();
110 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
111 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
112 return;
113 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000114 } else if (const CXXFunctionalCastExpr *FC
115 = dyn_cast<CXXFunctionalCastExpr>(E)) {
116 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
117 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
118 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000119 }
John McCall2351cb92010-04-06 22:24:14 +0000120 // Diagnose "(void*) blah" as a typo for "(void) blah".
121 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
122 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
123 QualType T = TI->getType();
124
125 // We really do want to use the non-canonical type here.
126 if (T == Context.VoidPtrTy) {
127 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
128
129 Diag(Loc, diag::warn_unused_voidptr)
130 << FixItHint::CreateRemoval(TL.getStarLoc());
131 return;
132 }
133 }
134
Douglas Gregorcb2b6622010-07-15 18:47:04 +0000135 DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000136}
137
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000138Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000139Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000140 MultiStmtArg elts, bool isStmtExpr) {
141 unsigned NumElts = elts.size();
142 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000143 // If we're in C89 mode, check that we don't have any decls after stmts. If
144 // so, emit an extension diagnostic.
145 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
146 // Note that __extension__ can be around a decl.
147 unsigned i = 0;
148 // Skip over all declarations.
149 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
150 /*empty*/;
151
152 // We found the end of the list or a statement. Scan for another declstmt.
153 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
154 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattnerd864daf2007-08-27 04:29:41 +0000156 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000157 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000158 Diag(D->getLocation(), diag::ext_mixed_decls_code);
159 }
160 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000161 // Warn about unused expressions in statements.
162 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000163 // Ignore statements that are last in a statement expression.
164 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000165 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000166
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000167 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000168 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000169
Ted Kremenek5a201952009-02-07 01:47:29 +0000170 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000171}
172
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000173Action::OwningStmtResult
174Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
175 SourceLocation DotDotDotLoc, ExprArg rhsval,
Chris Lattner34a22092009-03-04 04:23:07 +0000176 SourceLocation ColonLoc) {
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000177 assert((lhsval.get() != 0) && "missing expression in case statement");
178
Steve Naroff8eeeb132007-05-08 21:09:37 +0000179 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000180 // However, GCC allows any evaluatable integer expression.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000181 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
Mike Stump11289f42009-09-09 15:08:12 +0000182 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000183 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner34a22092009-03-04 04:23:07 +0000184 return StmtError();
Steve Naroff8eeeb132007-05-08 21:09:37 +0000185
Chris Lattner46eeb222007-07-18 02:28:47 +0000186 // GCC extension: The expression shall be an integer constant.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000187
188 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000189 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
190 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000191 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000192 rhsval = 0;
193 }
194
Chris Lattner96b31392009-04-18 20:10:59 +0000195 if (getSwitchStack().empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000196 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000197 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000198 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000199
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000200 // Only now release the smart pointers.
201 lhsval.release();
202 rhsval.release();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000203 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
204 ColonLoc);
Chris Lattner96b31392009-04-18 20:10:59 +0000205 getSwitchStack().back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000206 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000207}
208
Chris Lattner34a22092009-03-04 04:23:07 +0000209/// ActOnCaseStmtBody - This installs a statement as the body of a case.
210void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
211 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000212 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Chris Lattner34a22092009-03-04 04:23:07 +0000213 CS->setSubStmt(SubStmt);
214}
215
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000216Action::OwningStmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000217Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000218 StmtArg subStmt, Scope *CurScope) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000219 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000220
Chris Lattner96b31392009-04-18 20:10:59 +0000221 if (getSwitchStack().empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000222 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000223 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000224 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000225
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000226 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Chris Lattner96b31392009-04-18 20:10:59 +0000227 getSwitchStack().back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000228 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000229}
230
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000231Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000232Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000233 SourceLocation ColonLoc, StmtArg subStmt) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000234 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Steve Naroffd123bd02009-02-28 16:48:43 +0000235 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000236 LabelStmt *&LabelDecl = getLabelMap()[II];
Steve Naroffd123bd02009-02-28 16:48:43 +0000237
Chris Lattnere2473062007-05-28 06:28:18 +0000238 // If not forward referenced or defined already, just create a new LabelStmt.
Steve Naroff846b1ec2009-03-13 15:38:40 +0000239 if (LabelDecl == 0)
240 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000241
Chris Lattnereefa10e2007-05-28 06:56:27 +0000242 assert(LabelDecl->getID() == II && "Label mismatch!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000243
Chris Lattnere2473062007-05-28 06:28:18 +0000244 // Otherwise, this label was either forward reference or multiply defined. If
245 // multiply defined, reject it now.
246 if (LabelDecl->getSubStmt()) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000247 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
Chris Lattner0369c572008-11-23 23:12:31 +0000248 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000249 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000250 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000251
Chris Lattnere2473062007-05-28 06:28:18 +0000252 // Otherwise, this label was forward declared, and we just found its real
253 // definition. Fill in the forward definition and return it.
254 LabelDecl->setIdentLoc(IdentLoc);
Chris Lattner39407372007-07-21 03:00:26 +0000255 LabelDecl->setSubStmt(SubStmt);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000256 return Owned(LabelDecl);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000257}
258
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000259Action::OwningStmtResult
John McCall48871652010-08-21 09:40:31 +0000260Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000261 StmtArg ThenVal, SourceLocation ElseLoc,
262 StmtArg ElseVal) {
Anders Carlsson52627462009-05-17 18:26:53 +0000263 OwningExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000264
Douglas Gregor633caca2009-11-23 23:44:04 +0000265 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000266 if (CondVar) {
267 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000268 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000269 if (CondResult.isInvalid())
270 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000271 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000272 Expr *ConditionExpr = CondResult.takeAs<Expr>();
273 if (!ConditionExpr)
274 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000275
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000276 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000277 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000278
Anders Carlssondb83d772007-10-10 20:50:11 +0000279 // Warn if the if block has a null body without an else value.
280 // this helps prevent bugs due to typos, such as
281 // if (condition);
282 // do_stuff();
Mike Stump11289f42009-09-09 15:08:12 +0000283 if (!ElseVal.get()) {
Anders Carlssondb83d772007-10-10 20:50:11 +0000284 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
285 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
286 }
287
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000288 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
289 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000290
Anders Carlsson52627462009-05-17 18:26:53 +0000291 CondResult.release();
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000292 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000293 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000294}
Steve Naroff86272ea2007-05-29 02:14:17 +0000295
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000296/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
297/// the specified width and sign. If an overflow occurs, detect it and emit
298/// the specified diagnostic.
299void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
300 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000301 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000302 unsigned DiagID) {
303 // Perform a conversion to the promoted condition type if needed.
304 if (NewWidth > Val.getBitWidth()) {
305 // If this is an extension, just do it.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000306 Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000307 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000308
309 // If the input was signed and negative and the output is
310 // unsigned, don't bother to warn: this is implementation-defined
311 // behavior.
312 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000313 } else if (NewWidth < Val.getBitWidth()) {
314 // If this is a truncation, check for overflow.
315 llvm::APSInt ConvVal(Val);
316 ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000317 ConvVal.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000318 ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000319 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000320 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000321 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000323 // Regardless of whether a diagnostic was emitted, really do the
324 // truncation.
325 Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000326 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000327 } else if (NewSign != Val.isSigned()) {
328 // Convert the sign to match the sign of the condition. This can cause
329 // overflow as well: unsigned(INTMIN)
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000330 // We don't diagnose this overflow, because it is implementation-defined
331 // behavior.
332 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000333 llvm::APSInt OldVal(Val);
334 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000335 }
336}
337
Chris Lattner67998452007-08-23 18:29:20 +0000338namespace {
339 struct CaseCompareFunctor {
340 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
341 const llvm::APSInt &RHS) {
342 return LHS.first < RHS;
343 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000344 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
345 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
346 return LHS.first < RHS.first;
347 }
Chris Lattner67998452007-08-23 18:29:20 +0000348 bool operator()(const llvm::APSInt &LHS,
349 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
350 return LHS < RHS.first;
351 }
352 };
353}
354
Chris Lattner4b2ff022007-09-21 18:15:22 +0000355/// CmpCaseVals - Comparison predicate for sorting case values.
356///
357static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
358 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
359 if (lhs.first < rhs.first)
360 return true;
361
362 if (lhs.first == rhs.first &&
363 lhs.second->getCaseLoc().getRawEncoding()
364 < rhs.second->getCaseLoc().getRawEncoding())
365 return true;
366 return false;
367}
368
Douglas Gregorbd6839732010-02-08 22:24:16 +0000369/// CmpEnumVals - Comparison predicate for sorting enumeration values.
370///
371static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
372 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
373{
374 return lhs.first < rhs.first;
375}
376
377/// EqEnumVals - Comparison preficate for uniqing enumeration values.
378///
379static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
380 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
381{
382 return lhs.first == rhs.first;
383}
384
Chris Lattnera96d4272009-10-16 16:45:22 +0000385/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
386/// potentially integral-promoted expression @p expr.
387static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
John McCall45d30c32010-06-12 01:56:02 +0000388 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000389 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
390 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +0000391 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
Chris Lattnera96d4272009-10-16 16:45:22 +0000392 return TypeBeforePromotion;
393 }
394 }
395 return expr->getType();
396}
397
Douglas Gregore60e41a2010-05-06 17:25:47 +0000398Action::OwningStmtResult
399Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, ExprArg Cond,
John McCall48871652010-08-21 09:40:31 +0000400 Decl *CondVar) {
Douglas Gregore60e41a2010-05-06 17:25:47 +0000401 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000402 if (CondVar) {
403 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor12cc7ee2010-05-06 21:39:56 +0000404 OwningExprResult CondE = CheckConditionVariable(ConditionVar, SourceLocation(), false);
405 if (CondE.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000406 return StmtError();
Douglas Gregor12cc7ee2010-05-06 21:39:56 +0000407
408 Cond = move(CondE);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000409 }
410
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000411 if (!Cond.get())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000412 return StmtError();
413
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000414 Expr *CondExpr = static_cast<Expr *>(Cond.get());
415 OwningExprResult ConvertedCond
416 = ConvertToIntegralOrEnumerationType(SwitchLoc, move(Cond),
417 PDiag(diag::err_typecheck_statement_requires_integer),
418 PDiag(diag::err_switch_incomplete_class_type)
419 << CondExpr->getSourceRange(),
420 PDiag(diag::err_switch_explicit_conversion),
421 PDiag(diag::note_switch_conversion),
422 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor4799d032010-06-30 00:20:43 +0000423 PDiag(diag::note_switch_conversion),
424 PDiag(0));
Douglas Gregorf4ea7252010-06-29 23:17:37 +0000425 if (ConvertedCond.isInvalid())
426 return StmtError();
427
428 CondExpr = ConvertedCond.takeAs<Expr>();
429
John McCall48871652010-08-21 09:40:31 +0000430 if (!CondVar) {
Douglas Gregore60e41a2010-05-06 17:25:47 +0000431 CondExpr = MaybeCreateCXXExprWithTemporaries(CondExpr);
432 if (!CondExpr)
433 return StmtError();
434 }
John McCalla95172b2010-08-01 00:26:45 +0000435
436 setFunctionHasBranchIntoScope();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000437
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000438 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, CondExpr);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000439 getSwitchStack().push_back(SS);
440 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000441}
442
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000443Action::OwningStmtResult
444Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
445 StmtArg Body) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000446 Stmt *BodyStmt = Body.takeAs<Stmt>();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000447
Chris Lattner96b31392009-04-18 20:10:59 +0000448 SwitchStmt *SS = getSwitchStack().back();
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000449 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
450
Steve Naroff42a350a2007-09-01 21:08:38 +0000451 SS->setBody(BodyStmt, SwitchLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000452 getSwitchStack().pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000453
Douglas Gregorb412e172010-07-25 18:17:45 +0000454 if (SS->getCond() == 0)
Douglas Gregor3ff3af42009-11-25 06:20:02 +0000455 return StmtError();
Douglas Gregor3ff3af42009-11-25 06:20:02 +0000456
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000457 Expr *CondExpr = SS->getCond();
John McCalld3dfbd62010-05-18 03:19:21 +0000458 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000459 QualType CondTypeBeforePromotion =
460 GetTypeBeforeIntegralPromotion(CondExpr);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000461
Douglas Gregor7fdcbaf22009-11-25 15:17:36 +0000462 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
463 UsualUnaryConversions(CondExpr);
Douglas Gregor11075552009-11-25 05:02:21 +0000464 QualType CondType = CondExpr->getType();
Douglas Gregord0c22e02009-11-23 13:46:08 +0000465 SS->setCond(CondExpr);
466
Chris Lattnera96d4272009-10-16 16:45:22 +0000467 // C++ 6.4.2.p2:
468 // Integral promotions are performed (on the switch condition).
469 //
470 // A case value unrepresentable by the original switch condition
471 // type (before the promotion) doesn't make sense, even when it can
472 // be represented by the promoted type. Therefore we need to find
473 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000474 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000475 // We have already converted the expression to an integral or enumeration
476 // type, when we started the switch statement. If we don't have an
477 // appropriate type now, just return an error.
478 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000479 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000480
Chris Lattner4ebae652010-04-16 23:34:13 +0000481 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000482 // switch(bool_expr) {...} is often a programmer error, e.g.
483 // switch(n && mask) { ... } // Doh - should be "n & mask".
484 // One can always use an if statement instead of switch(bool_expr).
485 Diag(SwitchLoc, diag::warn_bool_switch_condition)
486 << CondExpr->getSourceRange();
487 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000488 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000489
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000490 // Get the bitwidth of the switched-on value before promotions. We must
491 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000492 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000493 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000494 unsigned CondWidth
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000495 = HasDependentValue? 0
Chris Lattnera96d4272009-10-16 16:45:22 +0000496 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
497 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000499 // Accumulate all of the case values in a vector so that we can sort them
500 // and detect duplicates. This vector contains the APInt for the case after
501 // it has been converted to the condition type.
Chris Lattner67998452007-08-23 18:29:20 +0000502 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
503 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000505 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000506 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
507 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000509 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner10cb5e52007-08-23 06:23:56 +0000511 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000512
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000513 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000514 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000515
Anders Carlsson51873c22007-07-22 07:07:56 +0000516 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000517 if (TheDefaultStmt) {
518 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000519 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000520
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000521 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000522 // we'll return a valid AST. This requires recursing down the AST and
523 // finding it, not something we are set up to do right now. For now,
524 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000525 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000526 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000527 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000529 } else {
530 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000532 // We already verified that the expression has a i-c-e value (C99
533 // 6.8.4.2p3) - get that value now.
Chris Lattnera65e1f32008-01-16 19:17:22 +0000534 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000535
536 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
537 HasDependentValue = true;
538 break;
539 }
Mike Stump11289f42009-09-09 15:08:12 +0000540
Anders Carlsson59689ed2008-11-22 21:04:56 +0000541 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000542
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000543 // Convert the value to the same width/sign as the condition.
544 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
545 CS->getLHS()->getLocStart(),
546 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000547
Chris Lattnera65e1f32008-01-16 19:17:22 +0000548 // If the LHS is not the same type as the condition, insert an implicit
549 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000550 ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
Chris Lattnera65e1f32008-01-16 19:17:22 +0000551 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattner10cb5e52007-08-23 06:23:56 +0000553 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000554 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000555 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000556 CS->getRHS()->isValueDependent()) {
557 HasDependentValue = true;
558 break;
559 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000560 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000561 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000562 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000563 }
564 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000565
566 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000567 // If we don't have a default statement, check whether the
568 // condition is constant.
569 llvm::APSInt ConstantCondValue;
570 bool HasConstantCond = false;
571 bool ShouldCheckConstantCond = false;
572 if (!HasDependentValue && !TheDefaultStmt) {
573 Expr::EvalResult Result;
574 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
575 if (HasConstantCond) {
576 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
577 ConstantCondValue = Result.Val.getInt();
578 ShouldCheckConstantCond = true;
579
580 assert(ConstantCondValue.getBitWidth() == CondWidth &&
581 ConstantCondValue.isSigned() == CondIsSigned);
582 }
583 }
584
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000585 // Sort all the scalar case values so we can easily detect duplicates.
586 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
587
588 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000589 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
590 if (ShouldCheckConstantCond &&
591 CaseVals[i].first == ConstantCondValue)
592 ShouldCheckConstantCond = false;
593
594 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000595 // If we have a duplicate, report it.
Mike Stump11289f42009-09-09 15:08:12 +0000596 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCalld3dfbd62010-05-18 03:19:21 +0000597 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
598 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000599 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000600 // FIXME: We really want to remove the bogus case stmt from the
601 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000602 CaseListIsErroneous = true;
603 }
604 }
605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000607 // Detect duplicate case ranges, which usually don't exist at all in
608 // the first place.
609 if (!CaseRanges.empty()) {
610 // Sort all the case ranges by their low value so we can easily detect
611 // overlaps between ranges.
612 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000613
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000614 // Scan the ranges, computing the high values and removing empty ranges.
615 std::vector<llvm::APSInt> HiVals;
616 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000617 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000618 CaseStmt *CR = CaseRanges[i].second;
619 Expr *Hi = CR->getRHS();
620 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000621
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000622 // Convert the value to the same width/sign as the condition.
623 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
624 CR->getRHS()->getLocStart(),
625 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000626
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000627 // If the LHS is not the same type as the condition, insert an implicit
628 // cast.
Eli Friedman06ed2a52009-10-20 08:27:19 +0000629 ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000630 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000631
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000632 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000633 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000634 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
635 << SourceRange(CR->getLHS()->getLocStart(),
636 CR->getRHS()->getLocEnd());
637 CaseRanges.erase(CaseRanges.begin()+i);
638 --i, --e;
639 continue;
640 }
John McCalld3dfbd62010-05-18 03:19:21 +0000641
642 if (ShouldCheckConstantCond &&
643 LoVal <= ConstantCondValue &&
644 ConstantCondValue <= HiVal)
645 ShouldCheckConstantCond = false;
646
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000647 HiVals.push_back(HiVal);
648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000650 // Rescan the ranges, looking for overlap with singleton values and other
651 // ranges. Since the range list is sorted, we only need to compare case
652 // ranges with their neighbors.
653 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
654 llvm::APSInt &CRLo = CaseRanges[i].first;
655 llvm::APSInt &CRHi = HiVals[i];
656 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000657
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000658 // Check to see whether the case range overlaps with any
659 // singleton cases.
660 CaseStmt *OverlapStmt = 0;
661 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000662
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000663 // Find the smallest value >= the lower bound. If I is in the
664 // case range, then we have overlap.
665 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
666 CaseVals.end(), CRLo,
667 CaseCompareFunctor());
668 if (I != CaseVals.end() && I->first < CRHi) {
669 OverlapVal = I->first; // Found overlap with scalar.
670 OverlapStmt = I->second;
671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000673 // Find the smallest value bigger than the upper bound.
674 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
675 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
676 OverlapVal = (I-1)->first; // Found overlap with scalar.
677 OverlapStmt = (I-1)->second;
678 }
Mike Stump11289f42009-09-09 15:08:12 +0000679
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000680 // Check to see if this case stmt overlaps with the subsequent
681 // case range.
682 if (i && CRLo <= HiVals[i-1]) {
683 OverlapVal = HiVals[i-1]; // Found overlap with range.
684 OverlapStmt = CaseRanges[i-1].second;
685 }
Mike Stump11289f42009-09-09 15:08:12 +0000686
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000687 if (OverlapStmt) {
688 // If we have a duplicate, report it.
689 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
690 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000691 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000692 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000693 // FIXME: We really want to remove the bogus case stmt from the
694 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000695 CaseListIsErroneous = true;
696 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000697 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000698 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000699
John McCalld3dfbd62010-05-18 03:19:21 +0000700 // Complain if we have a constant condition and we didn't find a match.
701 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
702 // TODO: it would be nice if we printed enums as enums, chars as
703 // chars, etc.
704 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
705 << ConstantCondValue.toString(10)
706 << CondExpr->getSourceRange();
707 }
708
709 // Check to see if switch is over an Enum and handles all of its
710 // values. We don't need to do this if there's a default
711 // statement or if we have a constant condition.
712 //
713 // TODO: we might want to check whether case values are out of the
714 // enum even if we don't want to check whether all cases are handled.
Douglas Gregor12ea0f42010-02-17 23:29:11 +0000715 const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000716 // If switch has default case, then ignore it.
John McCalld3dfbd62010-05-18 03:19:21 +0000717 if (!CaseListIsErroneous && !TheDefaultStmt && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000718 const EnumDecl *ED = ET->getDecl();
719 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
720 EnumValsTy EnumVals;
721
John McCalld3dfbd62010-05-18 03:19:21 +0000722 // Gather all enum values, set their type and sort them,
723 // allowing easier comparison with CaseVals.
724 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
725 EDI != ED->enumerator_end(); EDI++) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000726 llvm::APSInt Val = (*EDI)->getInitVal();
727 if(Val.getBitWidth() < CondWidth)
728 Val.extend(CondWidth);
Douglas Gregor56980d62010-06-29 17:12:35 +0000729 else if (Val.getBitWidth() > CondWidth)
730 Val.trunc(CondWidth);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000731 Val.setIsSigned(CondIsSigned);
732 EnumVals.push_back(std::make_pair(Val, (*EDI)));
733 }
734 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000735 EnumValsTy::iterator EIend =
736 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Douglas Gregorbd6839732010-02-08 22:24:16 +0000737 // See which case values aren't in enum
738 EnumValsTy::const_iterator EI = EnumVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000739 for (CaseValsTy::const_iterator CI = CaseVals.begin();
740 CI != CaseVals.end(); CI++) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000741 while (EI != EIend && EI->first < CI->first)
742 EI++;
743 if (EI == EIend || EI->first > CI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000744 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
745 << ED->getDeclName();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000746 }
747 // See which of case ranges aren't in enum
748 EI = EnumVals.begin();
John McCalld3dfbd62010-05-18 03:19:21 +0000749 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
750 RI != CaseRanges.end() && EI != EIend; RI++) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000751 while (EI != EIend && EI->first < RI->first)
752 EI++;
753
754 if (EI == EIend || EI->first != RI->first) {
John McCalld3dfbd62010-05-18 03:19:21 +0000755 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
756 << ED->getDeclName();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000757 }
758
759 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
760 while (EI != EIend && EI->first < Hi)
761 EI++;
762 if (EI == EIend || EI->first != Hi)
John McCalld3dfbd62010-05-18 03:19:21 +0000763 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
764 << ED->getDeclName();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000765 }
766 //Check which enum vals aren't in switch
767 CaseValsTy::const_iterator CI = CaseVals.begin();
768 CaseRangesTy::const_iterator RI = CaseRanges.begin();
769 EI = EnumVals.begin();
770 for (; EI != EIend; EI++) {
771 //Drop unneeded case values
772 llvm::APSInt CIVal;
773 while (CI != CaseVals.end() && CI->first < EI->first)
774 CI++;
775
776 if (CI != CaseVals.end() && CI->first == EI->first)
777 continue;
778
779 //Drop unneeded case ranges
780 for (; RI != CaseRanges.end(); RI++) {
781 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
782 if (EI->first <= Hi)
783 break;
784 }
785
786 if (RI == CaseRanges.end() || EI->first < RI->first)
John McCalld3dfbd62010-05-18 03:19:21 +0000787 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
788 << EI->second->getDeclName();
Douglas Gregorbd6839732010-02-08 22:24:16 +0000789 }
790 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000791 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000792
Mike Stump87c57ac2009-05-16 07:39:55 +0000793 // FIXME: If the case list was broken is some way, we don't have a good system
794 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000795 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000796 return StmtError();
797
798 Switch.release();
799 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000800}
801
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000802Action::OwningStmtResult
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000803Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall48871652010-08-21 09:40:31 +0000804 Decl *CondVar, StmtArg Body) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000805 OwningExprResult CondResult(Cond.release());
806
Douglas Gregor680f8612009-11-24 21:15:44 +0000807 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000808 if (CondVar) {
809 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000810 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000811 if (CondResult.isInvalid())
812 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +0000813 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000814 Expr *ConditionExpr = CondResult.takeAs<Expr>();
815 if (!ConditionExpr)
816 return StmtError();
817
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000818 Stmt *bodyStmt = Body.takeAs<Stmt>();
819 DiagnoseUnusedExprResult(bodyStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000821 CondResult.release();
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000822 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
823 bodyStmt, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000824}
825
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000826Action::OwningStmtResult
827Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
Chris Lattner815b70e2009-06-12 23:04:47 +0000828 SourceLocation WhileLoc, SourceLocation CondLParen,
829 ExprArg Cond, SourceLocation CondRParen) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000830 Expr *condExpr = Cond.takeAs<Expr>();
Steve Naroff66356bd2007-09-16 14:56:35 +0000831 assert(condExpr && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000832
John McCalld5707ab2009-10-12 21:59:07 +0000833 if (CheckBooleanCondition(condExpr, DoLoc)) {
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000834 Cond = condExpr;
John McCalld5707ab2009-10-12 21:59:07 +0000835 return StmtError();
Douglas Gregor3daa82d2009-05-15 21:56:04 +0000836 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000837
Douglas Gregore60e41a2010-05-06 17:25:47 +0000838 condExpr = MaybeCreateCXXExprWithTemporaries(condExpr);
839 if (!condExpr)
840 return StmtError();
841
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000842 Stmt *bodyStmt = Body.takeAs<Stmt>();
843 DiagnoseUnusedExprResult(bodyStmt);
844
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000845 Cond.release();
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000846 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
Chris Lattner815b70e2009-06-12 23:04:47 +0000847 WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000848}
849
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000850Action::OwningStmtResult
851Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall48871652010-08-21 09:40:31 +0000852 StmtArg first, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000853 FullExprArg third,
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000854 SourceLocation RParenLoc, StmtArg body) {
855 Stmt *First = static_cast<Stmt*>(first.get());
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000856
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000857 if (!getLangOptions().CPlusPlus) {
858 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000859 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
860 // declare identifiers for objects having storage class 'auto' or
861 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000862 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
863 DI!=DE; ++DI) {
864 VarDecl *VD = dyn_cast<VarDecl>(*DI);
865 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
866 VD = 0;
867 if (VD == 0)
868 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
869 // FIXME: mark decl erroneous!
870 }
Chris Lattner39f920f2007-08-28 05:03:08 +0000871 }
Steve Naroff86272ea2007-05-29 02:14:17 +0000872 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000873
874 OwningExprResult SecondResult(second.release());
875 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000876 if (secondVar) {
877 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000878 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000879 if (SecondResult.isInvalid())
880 return StmtError();
881 }
882
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000883 Expr *Third = third.release().takeAs<Expr>();
884 Stmt *Body = static_cast<Stmt*>(body.get());
885
Anders Carlsson1682af52009-08-01 01:39:59 +0000886 DiagnoseUnusedExprResult(First);
887 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000888 DiagnoseUnusedExprResult(Body);
889
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000890 first.release();
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000891 body.release();
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000892 return Owned(new (Context) ForStmt(Context, First,
893 SecondResult.takeAs<Expr>(), ConditionVar,
894 Third, Body, ForLoc, LParenLoc,
895 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000896}
897
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000898Action::OwningStmtResult
899Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
900 SourceLocation LParenLoc,
901 StmtArg first, ExprArg second,
902 SourceLocation RParenLoc, StmtArg body) {
903 Stmt *First = static_cast<Stmt*>(first.get());
904 Expr *Second = static_cast<Expr*>(second.get());
905 Stmt *Body = static_cast<Stmt*>(body.get());
Fariborz Jahanian93977672008-01-10 20:33:58 +0000906 if (First) {
907 QualType FirstType;
908 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +0000909 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000910 return StmtError(Diag((*DS->decl_begin())->getLocation(),
911 diag::err_toomany_element_decls));
912
Chris Lattner529efc72009-03-28 06:33:19 +0000913 Decl *D = DS->getSingleDecl();
Ted Kremenek11b00422008-10-06 20:58:11 +0000914 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +0000915 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
916 // declare identifiers for objects having storage class 'auto' or
917 // 'register'.
Steve Naroff08899ff2008-04-15 22:42:06 +0000918 VarDecl *VD = cast<VarDecl>(D);
919 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000920 return StmtError(Diag(VD->getLocation(),
921 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000922 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +0000923 Expr *FirstE = cast<Expr>(First);
924 if (!FirstE->isTypeDependent() &&
925 FirstE->isLvalue(Context) != Expr::LV_Valid)
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000926 return StmtError(Diag(First->getLocStart(),
927 diag::err_selector_element_not_lvalue)
928 << First->getSourceRange());
929
Mike Stump11289f42009-09-09 15:08:12 +0000930 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +0000931 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000932 if (!FirstType->isDependentType() &&
933 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +0000934 !FirstType->isBlockPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000935 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000936 << FirstType << First->getSourceRange();
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000937 }
Douglas Gregorf68a5082010-04-22 23:10:45 +0000938 if (Second && !Second->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +0000939 DefaultFunctionArrayLvalueConversion(Second);
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000940 QualType SecondType = Second->getType();
Steve Naroff79d12152009-07-16 15:41:00 +0000941 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerf490e152008-11-19 05:27:50 +0000942 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000943 << SecondType << Second->getSourceRange();
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000944 else if (const ObjCObjectPointerType *OPT =
945 SecondType->getAsObjCInterfacePointerType()) {
946 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
947 IdentifierInfo* selIdent =
948 &Context.Idents.get("countByEnumeratingWithState");
949 KeyIdents.push_back(selIdent);
950 selIdent = &Context.Idents.get("objects");
951 KeyIdents.push_back(selIdent);
952 selIdent = &Context.Idents.get("count");
953 KeyIdents.push_back(selIdent);
954 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
955 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
956 if (!IDecl->isForwardDecl() &&
957 !IDecl->lookupInstanceMethod(CSelector)) {
Fariborz Jahanianb5a62462010-08-12 22:33:42 +0000958 // Must further look into private implementation methods.
Fariborz Jahanian68e69ca9f2010-08-12 22:25:42 +0000959 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
960 Diag(ForLoc, diag::warn_collection_expr_type)
961 << SecondType << CSelector << Second->getSourceRange();
962 }
963 }
964 }
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000965 }
Sebastian Redlfbfaafc2009-01-16 23:28:06 +0000966 first.release();
967 second.release();
968 body.release();
Ted Kremenek5a201952009-02-07 01:47:29 +0000969 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
970 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +0000971}
Chris Lattneraf8d5812006-11-10 05:07:45 +0000972
Sebastian Redl573feed2009-01-18 13:19:59 +0000973Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000974Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
Chris Lattneraf8d5812006-11-10 05:07:45 +0000975 IdentifierInfo *LabelII) {
Chris Lattnere2473062007-05-28 06:28:18 +0000976 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +0000977 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Chris Lattnere2473062007-05-28 06:28:18 +0000978
John McCalla95172b2010-08-01 00:26:45 +0000979 setFunctionHasBranchIntoScope();
980
Steve Naroff846b1ec2009-03-13 15:38:40 +0000981 // If we haven't seen this label yet, create a forward reference.
982 if (LabelDecl == 0)
Ted Kremenek5a201952009-02-07 01:47:29 +0000983 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
Sebastian Redl573feed2009-01-18 13:19:59 +0000984
Ted Kremenek5a201952009-02-07 01:47:29 +0000985 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000986}
Chris Lattner1c310502007-05-31 06:00:00 +0000987
Sebastian Redl573feed2009-01-18 13:19:59 +0000988Action::OwningStmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +0000989Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
Sebastian Redl573feed2009-01-18 13:19:59 +0000990 ExprArg DestExp) {
Eli Friedman8d7ff402009-03-26 00:18:06 +0000991 // Convert operand to void*
Eli Friedman6568eef2009-03-26 07:32:37 +0000992 Expr* E = DestExp.takeAs<Expr>();
Douglas Gregor30776d42009-05-16 00:20:29 +0000993 if (!E->isTypeDependent()) {
994 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +0000995 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Douglas Gregor30776d42009-05-16 00:20:29 +0000996 AssignConvertType ConvTy =
Chandler Carruth00216982010-01-31 10:26:25 +0000997 CheckSingleAssignmentConstraints(DestTy, E);
998 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +0000999 return StmtError();
1000 }
John McCalla95172b2010-08-01 00:26:45 +00001001
1002 setFunctionHasIndirectGoto();
1003
Douglas Gregor30776d42009-05-16 00:20:29 +00001004 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001005}
1006
Sebastian Redl573feed2009-01-18 13:19:59 +00001007Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001008Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001009 Scope *S = CurScope->getContinueParent();
1010 if (!S) {
1011 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001012 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001013 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001014
Ted Kremenek5a201952009-02-07 01:47:29 +00001015 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001016}
1017
Sebastian Redl573feed2009-01-18 13:19:59 +00001018Action::OwningStmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00001019Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00001020 Scope *S = CurScope->getBreakParent();
1021 if (!S) {
1022 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00001023 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00001024 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001025
Ted Kremenek5a201952009-02-07 01:47:29 +00001026 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001027}
1028
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001029/// \brief Determine whether a return statement is a candidate for the named
1030/// return value optimization (C++0x 12.8p34, bullet 1).
1031///
1032/// \param Ctx The context in which the return expression and type occur.
1033///
1034/// \param RetType The return type of the function or block.
1035///
1036/// \param RetExpr The expression being returned from the function or block.
1037///
1038/// \returns The NRVO candidate variable, if the return statement may use the
1039/// NRVO, or NULL if there is no such candidate.
1040static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1041 Expr *RetExpr) {
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001042 QualType ExprType = RetExpr->getType();
1043 // - in a return statement in a function with ...
1044 // ... a class return type ...
1045 if (!RetType->isRecordType())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001046 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001047 // ... the same cv-unqualified type as the function return type ...
1048 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001049 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001050 // ... the expression is the name of a non-volatile automatic object ...
1051 // We ignore parentheses here.
1052 // FIXME: Is this compliant? (Everyone else does it)
1053 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1054 if (!DR)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001055 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001056 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1057 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001058 return 0;
1059
1060 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
Douglas Gregor290c93e2010-05-15 06:46:45 +00001061 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1062 !VD->getType().isVolatileQualified())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001063 return VD;
1064
1065 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00001066}
1067
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001068/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroffc540d662008-09-03 18:15:37 +00001069///
Sebastian Redl573feed2009-01-18 13:19:59 +00001070Action::OwningStmtResult
Steve Naroffc540d662008-09-03 18:15:37 +00001071Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroffc540d662008-09-03 18:15:37 +00001072 // If this is the first return we've seen in the block, infer the type of
1073 // the block from it.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001074 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001075 if (CurBlock->ReturnType.isNull()) {
Steve Naroff3b1e1722008-09-16 22:25:10 +00001076 if (RetValExp) {
Steve Naroffc60873c2008-09-24 22:26:48 +00001077 // Don't call UsualUnaryConversions(), since we don't want to do
1078 // integer promotions here.
Douglas Gregorb92a1562010-02-03 00:27:59 +00001079 DefaultFunctionArrayLvalueConversion(RetValExp);
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001080 CurBlock->ReturnType = RetValExp->getType();
1081 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1082 // We have to remove a 'const' added to copied-in variable which was
1083 // part of the implementation spec. and not the actual qualifier for
1084 // the variable.
1085 if (CDRE->isConstQualAdded())
1086 CurBlock->ReturnType.removeConst();
1087 }
Steve Naroff3b1e1722008-09-16 22:25:10 +00001088 } else
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001089 CurBlock->ReturnType = Context.VoidTy;
Steve Naroffc540d662008-09-03 18:15:37 +00001090 }
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001091 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl573feed2009-01-18 13:19:59 +00001092
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001093 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
Mike Stump56ed2ea2009-04-29 21:40:37 +00001094 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1095 << getCurFunctionOrMethodDecl()->getDeclName();
1096 return StmtError();
1097 }
1098
Steve Naroffc540d662008-09-03 18:15:37 +00001099 // Otherwise, verify that this result type matches the previous one. We are
1100 // pickier with blocks than for normal functions because we don't have GCC
1101 // compatibility to worry about here.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001102 ReturnStmt *Result = 0;
Steve Naroffc540d662008-09-03 18:15:37 +00001103 if (CurBlock->ReturnType->isVoidType()) {
1104 if (RetValExp) {
1105 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroffc540d662008-09-03 18:15:37 +00001106 RetValExp = 0;
1107 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001108 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1109 } else if (!RetValExp) {
Sebastian Redl573feed2009-01-18 13:19:59 +00001110 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001111 } else {
1112 const VarDecl *NRVOCandidate = 0;
1113
1114 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1115 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001116
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001117 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1118 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1119 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001120
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001121 // In C++ the return statement is handled via a copy initialization.
1122 // the C version of which boils down to CheckSingleAssignmentConstraints.
1123 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1124 OwningExprResult Res = PerformCopyInitialization(
1125 InitializedEntity::InitializeResult(ReturnLoc,
1126 FnRetType,
1127 NRVOCandidate != 0),
1128 SourceLocation(),
1129 Owned(RetValExp));
1130 if (Res.isInvalid()) {
1131 // FIXME: Cleanup temporaries here, anyway?
1132 return StmtError();
1133 }
1134
1135 if (RetValExp)
1136 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
Mike Stump82f071f2009-02-04 22:31:32 +00001137
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001138 RetValExp = Res.takeAs<Expr>();
1139 if (RetValExp)
1140 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlsson6f923f82010-01-29 18:30:20 +00001141 }
1142
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001143 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroffc540d662008-09-03 18:15:37 +00001144 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001145
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001146 // If we need to check for the named return value optimization, save the
1147 // return statement in our scope for later processing.
1148 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1149 !CurContext->isDependentContext())
1150 FunctionScopes.back()->Returns.push_back(Result);
1151
1152 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00001153}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001154
Sebastian Redl573feed2009-01-18 13:19:59 +00001155Action::OwningStmtResult
Anders Carlssona1929472009-08-18 16:11:00 +00001156Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1157 Expr *RetValExp = rex.takeAs<Expr>();
Douglas Gregor9a28e842010-03-01 23:15:13 +00001158 if (getCurBlock())
Steve Naroffc540d662008-09-03 18:15:37 +00001159 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00001160
Chris Lattner79413952008-12-04 23:50:19 +00001161 QualType FnRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001162 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00001163 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00001164 if (FD->hasAttr<NoReturnAttr>() ||
1165 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00001166 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001167 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpd00bc1a2009-04-29 00:43:21 +00001168 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Narofff3833d72009-03-03 00:45:38 +00001169 FnRetType = MD->getResultType();
1170 else // If we don't have a function/method context, bail.
1171 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00001172
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001173 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00001174 if (FnRetType->isVoidType()) {
Douglas Gregor78b691a2009-10-01 23:25:31 +00001175 if (RetValExp && !RetValExp->isTypeDependent()) {
1176 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner27e5bef2008-12-18 02:01:17 +00001177 unsigned D = diag::ext_return_has_expr;
1178 if (RetValExp->getType()->isVoidType())
1179 D = diag::ext_return_has_void_expr;
Sebastian Redl573feed2009-01-18 13:19:59 +00001180
Chris Lattner0cb00d62008-12-18 02:03:48 +00001181 // return (some void expression); is legal in C++.
1182 if (D != diag::ext_return_has_void_expr ||
1183 !getLangOptions().CPlusPlus) {
1184 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1185 Diag(ReturnLoc, D)
1186 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1187 << RetValExp->getSourceRange();
1188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Anders Carlsson6e997b22009-12-15 20:51:39 +00001190 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
Steve Naroff6f49f5d2007-05-29 14:23:36 +00001191 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001192
1193 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1194 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001195 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1196 // C99 6.8.6.4p1 (ext_ since GCC warns)
1197 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1198
1199 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00001200 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001201 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00001202 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001203 Result = new (Context) ReturnStmt(ReturnLoc);
1204 } else {
1205 const VarDecl *NRVOCandidate = 0;
1206 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1207 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00001208
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001209 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1210 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1211 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00001212
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001213 // In C++ the return statement is handled via a copy initialization.
1214 // the C version of which boils down to CheckSingleAssignmentConstraints.
1215 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1216 OwningExprResult Res = PerformCopyInitialization(
1217 InitializedEntity::InitializeResult(ReturnLoc,
1218 FnRetType,
1219 NRVOCandidate != 0),
1220 SourceLocation(),
1221 Owned(RetValExp));
1222 if (Res.isInvalid()) {
1223 // FIXME: Cleanup temporaries here, anyway?
1224 return StmtError();
1225 }
Sebastian Redl573feed2009-01-18 13:19:59 +00001226
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001227 RetValExp = Res.takeAs<Expr>();
1228 if (RetValExp)
1229 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001230 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001231
1232 if (RetValExp)
1233 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1234 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00001235 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00001236
1237 // If we need to check for the named return value optimization, save the
1238 // return statement in our scope for later processing.
1239 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1240 !CurContext->isDependentContext())
1241 FunctionScopes.back()->Returns.push_back(Result);
1242
1243 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001244}
1245
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001246/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1247/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1248/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1249/// provide a strong guidance to not use it.
1250///
1251/// This method checks to see if the argument is an acceptable l-value and
1252/// returns false if it is a case we can handle.
1253static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00001254 // Type dependent expressions will be checked during instantiation.
1255 if (E->isTypeDependent())
1256 return false;
1257
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001258 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1259 return false; // Cool, this is an lvalue.
1260
1261 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1262 // are supposed to allow.
1263 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1264 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1265 if (!S.getLangOptions().HeinousExtensions)
1266 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1267 << E->getSourceRange();
1268 else
1269 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1270 << E->getSourceRange();
1271 // Accept, even if we emitted an error diagnostic.
1272 return false;
1273 }
1274
1275 // None of the above, just randomly invalid non-lvalue.
1276 return true;
1277}
1278
1279
Sebastian Redl24b8e152009-01-18 16:53:17 +00001280Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1281 bool IsSimple,
1282 bool IsVolatile,
1283 unsigned NumOutputs,
1284 unsigned NumInputs,
Anders Carlsson9a020f92010-01-30 22:25:16 +00001285 IdentifierInfo **Names,
Sebastian Redl24b8e152009-01-18 16:53:17 +00001286 MultiExprArg constraints,
1287 MultiExprArg exprs,
1288 ExprArg asmString,
1289 MultiExprArg clobbers,
Mike Stump90be58a2010-01-04 22:37:17 +00001290 SourceLocation RParenLoc,
1291 bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001292 unsigned NumClobbers = clobbers.size();
1293 StringLiteral **Constraints =
1294 reinterpret_cast<StringLiteral**>(constraints.get());
1295 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1296 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1297 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1298
Anders Carlsson570c3572009-01-27 20:38:24 +00001299 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner496acc12008-08-18 19:55:17 +00001301 // The parser verifies that there is a string literal here.
Chris Lattner07096892008-07-23 06:46:56 +00001302 if (AsmString->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001303 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1304 << AsmString->getSourceRange());
1305
Chris Lattner496acc12008-08-18 19:55:17 +00001306 for (unsigned i = 0; i != NumOutputs; i++) {
1307 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001308 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001309 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1310 << Literal->getSourceRange());
1311
Anders Carlsson9a020f92010-01-30 22:25:16 +00001312 llvm::StringRef OutputName;
1313 if (Names[i])
1314 OutputName = Names[i]->getName();
1315
1316 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001317 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001318 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001319 diag::err_asm_invalid_output_constraint)
1320 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00001321
Anders Carlssonf511f642007-11-27 04:11:28 +00001322 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00001323 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001324 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00001325 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001326 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00001327 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerd9725f72009-04-26 07:16:29 +00001330 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001331 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001332
Chris Lattner34b51e82009-05-03 05:55:43 +00001333 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1334
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001335 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00001336 StringLiteral *Literal = Constraints[i];
Chris Lattner07096892008-07-23 06:46:56 +00001337 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001338 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1339 << Literal->getSourceRange());
1340
Anders Carlsson9a020f92010-01-30 22:25:16 +00001341 llvm::StringRef InputName;
1342 if (Names[i])
1343 InputName = Names[i]->getName();
1344
1345 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foad7d0479f2009-05-21 09:52:38 +00001346 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00001347 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00001348 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001349 diag::err_asm_invalid_input_constraint)
1350 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00001351 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001352
Eli Friedman47e78572009-05-03 07:49:42 +00001353 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00001354
Anders Carlsson224fca82009-01-20 20:49:22 +00001355 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00001356 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00001357 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00001358 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001359 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00001360 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001361 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001362 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001363
Chris Lattnerd9725f72009-04-26 07:16:29 +00001364 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00001365 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00001366 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00001367 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00001368 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00001369 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00001370 }
Anders Carlsson224fca82009-01-20 20:49:22 +00001371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregorb92a1562010-02-03 00:27:59 +00001373 DefaultFunctionArrayLvalueConversion(Exprs[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner34b51e82009-05-03 05:55:43 +00001375 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00001376 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001377
Anders Carlsson290aa852007-11-25 00:25:21 +00001378 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00001379 for (unsigned i = 0; i != NumClobbers; i++) {
1380 StringLiteral *Literal = Clobbers[i];
Chris Lattner07096892008-07-23 06:46:56 +00001381 if (Literal->isWide())
Sebastian Redl24b8e152009-01-18 16:53:17 +00001382 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1383 << Literal->getSourceRange());
1384
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001385 llvm::StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00001386
Anders Carlsson96fe0b52010-01-30 19:34:25 +00001387 if (!Context.Target.isValidGCCRegisterName(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00001388 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00001389 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00001390 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00001391
1392 constraints.release();
1393 exprs.release();
1394 asmString.release();
1395 clobbers.release();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001396 AsmStmt *NS =
Anders Carlsson98323d22010-01-30 23:19:41 +00001397 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1398 NumOutputs, NumInputs, Names, Constraints, Exprs,
1399 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001400 // Validate the asm string, ensuring it makes sense given the operands we
1401 // have.
1402 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1403 unsigned DiagOffs;
1404 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00001405 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1406 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001407 DeleteStmt(NS);
1408 return StmtError();
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Chris Lattner34b51e82009-05-03 05:55:43 +00001411 // Validate tied input operands for type mismatches.
1412 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1413 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00001414
Chris Lattner34b51e82009-05-03 05:55:43 +00001415 // If this is a tied constraint, verify that the output and input have
1416 // either exactly the same type, or that they are int/ptr operands with the
1417 // same size (int/long, int*/long, are ok etc).
1418 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Chris Lattner34b51e82009-05-03 05:55:43 +00001420 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnercb66c732009-05-03 07:04:21 +00001421 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner28b05c82009-05-03 06:50:40 +00001422 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner2c295cf2009-05-03 05:59:17 +00001423 QualType InTy = InputExpr->getType();
1424 QualType OutTy = OutputExpr->getType();
1425 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00001426 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00001427
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001428 // Decide if the input and output are in the same domain (integer/ptr or
1429 // floating point.
1430 enum AsmDomain {
1431 AD_Int, AD_FP, AD_Other
1432 } InputDomain, OutputDomain;
1433
1434 if (InTy->isIntegerType() || InTy->isPointerType())
1435 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001436 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001437 InputDomain = AD_FP;
1438 else
1439 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00001440
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001441 if (OutTy->isIntegerType() || OutTy->isPointerType())
1442 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00001443 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001444 OutputDomain = AD_FP;
1445 else
1446 OutputDomain = AD_Other;
1447
1448 // They are ok if they are the same size and in the same domain. This
1449 // allows tying things like:
1450 // void* to int*
1451 // void* to int if they are the same size.
1452 // double to long double if they are the same size.
1453 //
1454 uint64_t OutSize = Context.getTypeSize(OutTy);
1455 uint64_t InSize = Context.getTypeSize(InTy);
1456 if (OutSize == InSize && InputDomain == OutputDomain &&
1457 InputDomain != AD_Other)
1458 continue;
1459
1460 // If the smaller input/output operand is not mentioned in the asm string,
1461 // then we can promote it and the asm string won't notice. Check this
1462 // case now.
1463 bool SmallerValueMentioned = false;
1464 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1465 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1466 if (!Piece.isOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001467
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001468 // If this is a reference to the input and if the input was the smaller
1469 // one, then we have to reject this asm.
1470 if (Piece.getOperandNo() == i+NumOutputs) {
1471 if (InSize < OutSize) {
1472 SmallerValueMentioned = true;
1473 break;
Chris Lattnercc1cde92009-05-03 08:32:32 +00001474 }
Chris Lattnercb66c732009-05-03 07:04:21 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001477 // If this is a reference to the input and if the input was the smaller
1478 // one, then we have to reject this asm.
1479 if (Piece.getOperandNo() == TiedTo) {
1480 if (InSize > OutSize) {
1481 SmallerValueMentioned = true;
1482 break;
1483 }
1484 }
Chris Lattner34b51e82009-05-03 05:55:43 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00001487 // If the smaller value wasn't mentioned in the asm string, and if the
1488 // output was a register, just extend the shorter one to the size of the
1489 // larger one.
1490 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1491 OutputConstraintInfos[TiedTo].allowsRegister())
1492 continue;
1493
Chris Lattner28b05c82009-05-03 06:50:40 +00001494 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00001495 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00001496 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00001497 << InputExpr->getSourceRange();
1498 DeleteStmt(NS);
1499 return StmtError();
1500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00001502 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00001503}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001504
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001505Action::OwningStmtResult
1506Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00001507 SourceLocation RParen, Decl *Parm,
Douglas Gregor96c79492010-04-23 22:50:49 +00001508 StmtArg Body) {
John McCall48871652010-08-21 09:40:31 +00001509 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00001510 if (Var && Var->isInvalidDecl())
1511 return StmtError();
1512
1513 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var,
Douglas Gregor96c79492010-04-23 22:50:49 +00001514 Body.takeAs<Stmt>()));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00001515}
1516
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001517Action::OwningStmtResult
1518Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001519 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1520 static_cast<Stmt*>(Body.release())));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00001521}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001522
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001523Action::OwningStmtResult
Douglas Gregor96c79492010-04-23 22:50:49 +00001524Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try,
1525 MultiStmtArg CatchStmts, StmtArg Finally) {
John McCalla95172b2010-08-01 00:26:45 +00001526 setFunctionHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00001527 unsigned NumCatchStmts = CatchStmts.size();
1528 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try.takeAs<Stmt>(),
1529 (Stmt **)CatchStmts.release(),
1530 NumCatchStmts,
1531 Finally.takeAs<Stmt>()));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001532}
1533
Douglas Gregor2900c162010-04-22 21:44:01 +00001534Sema::OwningStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1535 ExprArg ThrowE) {
1536 Expr *Throw = static_cast<Expr *>(ThrowE.get());
1537 if (Throw) {
1538 QualType ThrowType = Throw->getType();
1539 // Make sure the expression type is an ObjC pointer or "void *".
1540 if (!ThrowType->isDependentType() &&
1541 !ThrowType->isObjCObjectPointerType()) {
1542 const PointerType *PT = ThrowType->getAs<PointerType>();
1543 if (!PT || !PT->getPointeeType()->isVoidType())
1544 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1545 << Throw->getType() << Throw->getSourceRange());
1546 }
1547 }
1548
1549 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowE.takeAs<Expr>()));
1550}
1551
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001552Action::OwningStmtResult
Douglas Gregor2900c162010-04-22 21:44:01 +00001553Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw,
1554 Scope *CurScope) {
1555 if (!Throw.get()) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00001556 // @throw without an expression designates a rethrow (which much occur
1557 // in the context of an @catch clause).
1558 Scope *AtCatchParent = CurScope;
1559 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1560 AtCatchParent = AtCatchParent->getParent();
1561 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00001562 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
Douglas Gregor2900c162010-04-22 21:44:01 +00001563 }
1564
1565 return BuildObjCAtThrowStmt(AtLoc, move(Throw));
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00001566}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00001567
Sebastian Redl481bf3f2009-01-18 17:43:11 +00001568Action::OwningStmtResult
1569Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1570 StmtArg SynchBody) {
John McCalla95172b2010-08-01 00:26:45 +00001571 setFunctionHasBranchProtectedScope();
Chris Lattnerc70dd562009-04-21 06:01:00 +00001572
Chris Lattner3501d432009-04-21 06:11:25 +00001573 // Make sure the expression type is an ObjC pointer or "void *".
1574 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
Douglas Gregor6148de72010-04-22 22:01:21 +00001575 if (!SyncExpr->getType()->isDependentType() &&
1576 !SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001577 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattner3501d432009-04-21 06:11:25 +00001578 if (!PT || !PT->getPointeeType()->isVoidType())
1579 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1580 << SyncExpr->getType() << SyncExpr->getSourceRange());
1581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
1583 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001584 SynchExpr.takeAs<Stmt>(),
1585 SynchBody.takeAs<Stmt>()));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00001586}
Sebastian Redl54c04d42008-12-22 19:15:10 +00001587
1588/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1589/// and creates a proper catch handler from them.
1590Action::OwningStmtResult
John McCall48871652010-08-21 09:40:31 +00001591Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
Sebastian Redl54c04d42008-12-22 19:15:10 +00001592 StmtArg HandlerBlock) {
1593 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00001594 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00001595 cast_or_null<VarDecl>(ExDecl),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001596 HandlerBlock.takeAs<Stmt>()));
Sebastian Redl54c04d42008-12-22 19:15:10 +00001597}
Sebastian Redl9b244a82008-12-22 21:35:02 +00001598
Dan Gohman28ade552010-07-26 21:25:24 +00001599namespace {
1600
Sebastian Redl63c4da02009-07-29 17:15:45 +00001601class TypeWithHandler {
1602 QualType t;
1603 CXXCatchStmt *stmt;
1604public:
1605 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1606 : t(type), stmt(statement) {}
1607
John McCall8ccfcb52009-09-24 19:53:00 +00001608 // An arbitrary order is fine as long as it places identical
1609 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00001610 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001611 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001612 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00001613 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00001614 return false;
1615 else
1616 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1617 }
Mike Stump11289f42009-09-09 15:08:12 +00001618
Sebastian Redl63c4da02009-07-29 17:15:45 +00001619 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001620 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
Sebastian Redl63c4da02009-07-29 17:15:45 +00001623 QualType getQualType() const { return t; }
1624 CXXCatchStmt *getCatchStmt() const { return stmt; }
1625 SourceLocation getTypeSpecStartLoc() const {
1626 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1627 }
1628};
1629
Dan Gohman28ade552010-07-26 21:25:24 +00001630}
1631
Sebastian Redl9b244a82008-12-22 21:35:02 +00001632/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1633/// handlers and creates a try statement from them.
1634Action::OwningStmtResult
1635Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1636 MultiStmtArg RawHandlers) {
1637 unsigned NumHandlers = RawHandlers.size();
1638 assert(NumHandlers > 0 &&
1639 "The parser shouldn't call this if there are no handlers.");
1640 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1641
Sebastian Redl63c4da02009-07-29 17:15:45 +00001642 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00001643
1644 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl9b244a82008-12-22 21:35:02 +00001645 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00001646 if (!Handler->getExceptionDecl()) {
1647 if (i < NumHandlers - 1)
1648 return StmtError(Diag(Handler->getLocStart(),
1649 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00001650
Sebastian Redl63c4da02009-07-29 17:15:45 +00001651 continue;
1652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Sebastian Redl63c4da02009-07-29 17:15:45 +00001654 const QualType CaughtType = Handler->getCaughtType();
1655 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1656 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001657 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00001658
1659 // Detect handlers for the same type as an earlier one.
1660 if (NumHandlers > 1) {
1661 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00001662
Sebastian Redl63c4da02009-07-29 17:15:45 +00001663 TypeWithHandler prev = TypesWithHandlers[0];
1664 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1665 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00001666
Sebastian Redl63c4da02009-07-29 17:15:45 +00001667 if (curr == prev) {
1668 Diag(curr.getTypeSpecStartLoc(),
1669 diag::warn_exception_caught_by_earlier_handler)
1670 << curr.getCatchStmt()->getCaughtType().getAsString();
1671 Diag(prev.getTypeSpecStartLoc(),
1672 diag::note_previous_exception_handler)
1673 << prev.getCatchStmt()->getCaughtType().getAsString();
1674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
Sebastian Redl63c4da02009-07-29 17:15:45 +00001676 prev = curr;
1677 }
1678 }
Mike Stump11289f42009-09-09 15:08:12 +00001679
John McCalla95172b2010-08-01 00:26:45 +00001680 setFunctionHasBranchProtectedScope();
1681
Sebastian Redl9b244a82008-12-22 21:35:02 +00001682 // FIXME: We should detect handlers that cannot catch anything because an
1683 // earlier handler catches a superclass. Need to find a method that is not
1684 // quadratic for this.
1685 // Neither of these are explicitly forbidden, but every compiler detects them
1686 // and warns.
1687
1688 RawHandlers.release();
Sam Weiniga16b0dd2010-02-03 03:56:39 +00001689 return Owned(CXXTryStmt::Create(Context, TryLoc,
1690 static_cast<Stmt*>(TryBlock.release()),
1691 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00001692}