blob: 24489544e0628063eda7db07b45c831b99136a81 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Anders Carlsson51fe9962008-11-22 21:04:56 +000018#include "clang/AST/APValue.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000022#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000023#include "clang/AST/StmtObjC.h"
24#include "clang/AST/StmtCXX.h"
John McCall209acbd2010-04-06 22:24:14 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000026#include "clang/Lex/Preprocessor.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000027#include "clang/Basic/TargetInfo.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000031using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000032
John McCall60d7b3a2010-08-24 06:29:42 +000033StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000034 Expr *E = expr.get();
Steve Naroff1b273c42007-09-16 14:56:35 +000035 assert(E && "ActOnExprStmt(): missing expression");
Chris Lattner834a72a2008-07-25 23:18:17 +000036 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
37 // void expression for its side effects. Conversion to void allows any
38 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000039
Chris Lattner834a72a2008-07-25 23:18:17 +000040 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000041 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000042}
43
44
John McCall60d7b3a2010-08-24 06:29:42 +000045StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
Ted Kremenek8189cde2009-02-07 01:47:29 +000046 return Owned(new (Context) NullStmt(SemiLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
John McCall60d7b3a2010-08-24 06:29:42 +000049StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
Sebastian Redla60528c2008-12-21 12:04:03 +000050 SourceLocation StartLoc,
51 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000052 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner20401692009-04-12 20:13:14 +000054 // If we have an invalid decl, just return an error.
55 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000056
Chris Lattner24e1e702009-03-04 04:23:07 +000057 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000058}
59
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000060void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
61 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
62
63 // If we have an invalid decl, just return.
64 if (DG.isNull() || !DG.isSingleDecl()) return;
65 // suppress any potential 'unused variable' warning.
66 DG.getSingleDecl()->setUsed();
67}
68
Anders Carlsson636463e2009-07-30 22:17:18 +000069void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +000070 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
71 return DiagnoseUnusedExprResult(Label->getSubStmt());
72
Anders Carlsson75443112009-07-30 22:39:03 +000073 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +000074 if (!E)
75 return;
76
Anders Carlsson636463e2009-07-30 22:17:18 +000077 SourceLocation Loc;
78 SourceRange R1, R2;
Mike Stumpdf317bf2009-11-03 23:25:48 +000079 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +000080 return;
Mike Stump1eb44332009-09-09 15:08:12 +000081
Chris Lattner419cfb32009-08-16 16:57:27 +000082 // Okay, we have an unused result. Depending on what the base expression is,
83 // we might want to make a more specific diagnostic. Check for one of these
84 // cases now.
85 unsigned DiagID = diag::warn_unused_expr;
86 E = E->IgnoreParens();
Fariborz Jahanian09105f52009-08-20 17:02:02 +000087 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
Chris Lattner419cfb32009-08-16 16:57:27 +000088 DiagID = diag::warn_unused_property_expr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +000089
Douglas Gregor4dffad62010-02-11 22:55:30 +000090 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
91 E = Temps->getSubExpr();
Douglas Gregor4dffad62010-02-11 22:55:30 +000092
Chris Lattnerbc8d42c2009-10-13 04:53:48 +000093 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +000094 if (E->getType()->isVoidType())
95 return;
96
Chris Lattnerbc8d42c2009-10-13 04:53:48 +000097 // If the callee has attribute pure, const, or warn_unused_result, warn with
98 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +000099 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000100 if (FD->getAttr<WarnUnusedResultAttr>()) {
101 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
102 return;
103 }
104 if (FD->getAttr<PureAttr>()) {
105 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
106 return;
107 }
108 if (FD->getAttr<ConstAttr>()) {
109 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
110 return;
111 }
112 }
113 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000114 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
115 const ObjCMethodDecl *MD = ME->getMethodDecl();
116 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
117 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
118 return;
119 }
Douglas Gregord6e44a32010-04-16 22:09:46 +0000120 } else if (const CXXFunctionalCastExpr *FC
121 = dyn_cast<CXXFunctionalCastExpr>(E)) {
122 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
123 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
124 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000125 }
John McCall209acbd2010-04-06 22:24:14 +0000126 // Diagnose "(void*) blah" as a typo for "(void) blah".
127 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
128 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
129 QualType T = TI->getType();
130
131 // We really do want to use the non-canonical type here.
132 if (T == Context.VoidPtrTy) {
133 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
134
135 Diag(Loc, diag::warn_unused_voidptr)
136 << FixItHint::CreateRemoval(TL.getStarLoc());
137 return;
138 }
139 }
140
Douglas Gregor35e12c92010-07-15 18:47:04 +0000141 DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000142}
143
John McCall60d7b3a2010-08-24 06:29:42 +0000144StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000145Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000146 MultiStmtArg elts, bool isStmtExpr) {
147 unsigned NumElts = elts.size();
148 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000149 // If we're in C89 mode, check that we don't have any decls after stmts. If
150 // so, emit an extension diagnostic.
151 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
152 // Note that __extension__ can be around a decl.
153 unsigned i = 0;
154 // Skip over all declarations.
155 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
156 /*empty*/;
157
158 // We found the end of the list or a statement. Scan for another declstmt.
159 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
160 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000162 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000163 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000164 Diag(D->getLocation(), diag::ext_mixed_decls_code);
165 }
166 }
Chris Lattner98414c12007-08-31 21:49:55 +0000167 // Warn about unused expressions in statements.
168 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000169 // Ignore statements that are last in a statement expression.
170 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000171 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Anders Carlsson636463e2009-07-30 22:17:18 +0000173 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000174 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000175
Ted Kremenek8189cde2009-02-07 01:47:29 +0000176 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000177}
178
John McCall60d7b3a2010-08-24 06:29:42 +0000179StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000180Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
181 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000182 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000183 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000186 // However, GCC allows any evaluatable integer expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000187 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregordbb26db2009-05-15 23:57:33 +0000188 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner24e1e702009-03-04 04:23:07 +0000189 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000190
Chris Lattner6c36be52007-07-18 02:28:47 +0000191 // GCC extension: The expression shall be an integer constant.
Sebastian Redl117054a2008-12-28 16:13:43 +0000192
Douglas Gregordbb26db2009-05-15 23:57:33 +0000193 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
194 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000195 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl117054a2008-12-28 16:13:43 +0000196 }
197
John McCall781472f2010-08-25 08:40:02 +0000198 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000199 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000200 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000201 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000202
Douglas Gregordbb26db2009-05-15 23:57:33 +0000203 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
204 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000205 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000206 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000207}
208
Chris Lattner24e1e702009-03-04 04:23:07 +0000209/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000210void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner24e1e702009-03-04 04:23:07 +0000211 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000212 CS->setSubStmt(SubStmt);
213}
214
John McCall60d7b3a2010-08-24 06:29:42 +0000215StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000216Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000217 Stmt *SubStmt, Scope *CurScope) {
John McCall781472f2010-08-25 08:40:02 +0000218 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000219 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000220 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000221 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000222
Douglas Gregordbb26db2009-05-15 23:57:33 +0000223 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000224 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000225 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000226}
227
John McCall60d7b3a2010-08-24 06:29:42 +0000228StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000229Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
John McCall9ae2f072010-08-23 23:25:46 +0000230 SourceLocation ColonLoc, Stmt *SubStmt) {
Steve Narofff3cf8972009-02-28 16:48:43 +0000231 // Look up the record for this label identifier.
John McCall781472f2010-08-25 08:40:02 +0000232 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[II];
Steve Narofff3cf8972009-02-28 16:48:43 +0000233
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 // If not forward referenced or defined already, just create a new LabelStmt.
Steve Naroffcaaacec2009-03-13 15:38:40 +0000235 if (LabelDecl == 0)
236 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
Sebastian Redlde307472009-01-11 00:38:46 +0000237
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 assert(LabelDecl->getID() == II && "Label mismatch!");
Sebastian Redlde307472009-01-11 00:38:46 +0000239
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 // Otherwise, this label was either forward reference or multiply defined. If
241 // multiply defined, reject it now.
242 if (LabelDecl->getSubStmt()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000243 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000244 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000245 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 }
Sebastian Redlde307472009-01-11 00:38:46 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 // Otherwise, this label was forward declared, and we just found its real
249 // definition. Fill in the forward definition and return it.
250 LabelDecl->setIdentLoc(IdentLoc);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000251 LabelDecl->setSubStmt(SubStmt);
Sebastian Redlde307472009-01-11 00:38:46 +0000252 return Owned(LabelDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253}
254
John McCall60d7b3a2010-08-24 06:29:42 +0000255StmtResult
John McCalld226f652010-08-21 09:40:31 +0000256Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
John McCall9ae2f072010-08-23 23:25:46 +0000257 Stmt *thenStmt, SourceLocation ElseLoc,
258 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000259 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000261 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000262 if (CondVar) {
263 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000264 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000265 if (CondResult.isInvalid())
266 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000267 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000268 Expr *ConditionExpr = CondResult.takeAs<Expr>();
269 if (!ConditionExpr)
270 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000271
Anders Carlsson75443112009-07-30 22:39:03 +0000272 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000273
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000274 // Warn if the if block has a null body without an else value.
275 // this helps prevent bugs due to typos, such as
276 // if (condition);
277 // do_stuff();
Ted Kremenekb3198172010-09-16 00:37:05 +0000278 //
279 // NOTE: Do not emit this warning if the body is expanded from a macro.
John McCall9ae2f072010-08-23 23:25:46 +0000280 if (!elseStmt) {
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000281 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Ted Kremenekb3198172010-09-16 00:37:05 +0000282 if (!stmt->getLocStart().isMacroID())
283 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000284 }
285
Anders Carlsson75443112009-07-30 22:39:03 +0000286 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000288 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000289 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000290}
291
Chris Lattnerf4021e72007-08-23 05:46:52 +0000292/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
293/// the specified width and sign. If an overflow occurs, detect it and emit
294/// the specified diagnostic.
295void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
296 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000297 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000298 unsigned DiagID) {
299 // Perform a conversion to the promoted condition type if needed.
300 if (NewWidth > Val.getBitWidth()) {
301 // If this is an extension, just do it.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000302 Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000303 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000304
305 // If the input was signed and negative and the output is
306 // unsigned, don't bother to warn: this is implementation-defined
307 // behavior.
308 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000309 } else if (NewWidth < Val.getBitWidth()) {
310 // If this is a truncation, check for overflow.
311 llvm::APSInt ConvVal(Val);
312 ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000313 ConvVal.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000314 ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000315 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000316 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000317 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattnerf4021e72007-08-23 05:46:52 +0000319 // Regardless of whether a diagnostic was emitted, really do the
320 // truncation.
321 Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000322 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000323 } else if (NewSign != Val.isSigned()) {
324 // Convert the sign to match the sign of the condition. This can cause
325 // overflow as well: unsigned(INTMIN)
Douglas Gregor2853eac2010-02-18 00:56:01 +0000326 // We don't diagnose this overflow, because it is implementation-defined
327 // behavior.
328 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000329 llvm::APSInt OldVal(Val);
330 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000331 }
332}
333
Chris Lattner0471f5b2007-08-23 18:29:20 +0000334namespace {
335 struct CaseCompareFunctor {
336 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
337 const llvm::APSInt &RHS) {
338 return LHS.first < RHS;
339 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000340 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
341 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
342 return LHS.first < RHS.first;
343 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000344 bool operator()(const llvm::APSInt &LHS,
345 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
346 return LHS < RHS.first;
347 }
348 };
349}
350
Chris Lattner764a7ce2007-09-21 18:15:22 +0000351/// CmpCaseVals - Comparison predicate for sorting case values.
352///
353static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
354 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
355 if (lhs.first < rhs.first)
356 return true;
357
358 if (lhs.first == rhs.first &&
359 lhs.second->getCaseLoc().getRawEncoding()
360 < rhs.second->getCaseLoc().getRawEncoding())
361 return true;
362 return false;
363}
364
Douglas Gregorba915af2010-02-08 22:24:16 +0000365/// CmpEnumVals - Comparison predicate for sorting enumeration values.
366///
367static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
368 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
369{
370 return lhs.first < rhs.first;
371}
372
373/// EqEnumVals - Comparison preficate for uniqing enumeration values.
374///
375static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
376 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
377{
378 return lhs.first == rhs.first;
379}
380
Chris Lattner5f048812009-10-16 16:45:22 +0000381/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
382/// potentially integral-promoted expression @p expr.
383static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
John McCall6907fbe2010-06-12 01:56:02 +0000384 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
Chris Lattner5f048812009-10-16 16:45:22 +0000385 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
386 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000387 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
Chris Lattner5f048812009-10-16 16:45:22 +0000388 return TypeBeforePromotion;
389 }
390 }
391 return expr->getType();
392}
393
John McCall60d7b3a2010-08-24 06:29:42 +0000394StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000395Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000396 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000397 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000398
Douglas Gregor586596f2010-05-06 17:25:47 +0000399 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000400 if (CondVar) {
401 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000402 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
403 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000404 return StmtError();
Douglas Gregoreecf38f2010-05-06 21:39:56 +0000405
John McCall9ae2f072010-08-23 23:25:46 +0000406 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000407 }
408
John McCall9ae2f072010-08-23 23:25:46 +0000409 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000410 return StmtError();
411
John McCall9ae2f072010-08-23 23:25:46 +0000412 CondResult
413 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorc30614b2010-06-29 23:17:37 +0000414 PDiag(diag::err_typecheck_statement_requires_integer),
415 PDiag(diag::err_switch_incomplete_class_type)
John McCall9ae2f072010-08-23 23:25:46 +0000416 << Cond->getSourceRange(),
Douglas Gregorc30614b2010-06-29 23:17:37 +0000417 PDiag(diag::err_switch_explicit_conversion),
418 PDiag(diag::note_switch_conversion),
419 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000420 PDiag(diag::note_switch_conversion),
421 PDiag(0));
John McCall9ae2f072010-08-23 23:25:46 +0000422 if (CondResult.isInvalid()) return StmtError();
423 Cond = CondResult.take();
Douglas Gregorc30614b2010-06-29 23:17:37 +0000424
John McCalld226f652010-08-21 09:40:31 +0000425 if (!CondVar) {
John McCall9ae2f072010-08-23 23:25:46 +0000426 CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
427 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000428 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000429 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000430 }
John McCallb60a77e2010-08-01 00:26:45 +0000431
John McCall781472f2010-08-25 08:40:02 +0000432 getCurFunction()->setHasBranchIntoScope();
Douglas Gregor586596f2010-05-06 17:25:47 +0000433
John McCall9ae2f072010-08-23 23:25:46 +0000434 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000435 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000436 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000437}
438
John McCall60d7b3a2010-08-24 06:29:42 +0000439StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000440Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
441 Stmt *BodyStmt) {
442 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000443 assert(SS == getCurFunction()->SwitchStack.back() &&
444 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000445
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000446 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000447 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000448
Douglas Gregorff331c12010-07-25 18:17:45 +0000449 if (SS->getCond() == 0)
Douglas Gregorbe724ba2009-11-25 06:20:02 +0000450 return StmtError();
Douglas Gregorbe724ba2009-11-25 06:20:02 +0000451
Chris Lattnerf4021e72007-08-23 05:46:52 +0000452 Expr *CondExpr = SS->getCond();
John McCall0fb97082010-05-18 03:19:21 +0000453 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000454 QualType CondTypeBeforePromotion =
455 GetTypeBeforeIntegralPromotion(CondExpr);
Sebastian Redlde307472009-01-11 00:38:46 +0000456
Douglas Gregor0de55e72009-11-25 15:17:36 +0000457 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
458 UsualUnaryConversions(CondExpr);
Douglas Gregora0d3ca12009-11-25 05:02:21 +0000459 QualType CondType = CondExpr->getType();
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000460 SS->setCond(CondExpr);
461
Chris Lattner5f048812009-10-16 16:45:22 +0000462 // C++ 6.4.2.p2:
463 // Integral promotions are performed (on the switch condition).
464 //
465 // A case value unrepresentable by the original switch condition
466 // type (before the promotion) doesn't make sense, even when it can
467 // be represented by the promoted type. Therefore we need to find
468 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000469 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000470 // We have already converted the expression to an integral or enumeration
471 // type, when we started the switch statement. If we don't have an
472 // appropriate type now, just return an error.
473 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000474 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000475
Chris Lattner2b334bb2010-04-16 23:34:13 +0000476 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000477 // switch(bool_expr) {...} is often a programmer error, e.g.
478 // switch(n && mask) { ... } // Doh - should be "n & mask".
479 // One can always use an if statement instead of switch(bool_expr).
480 Diag(SwitchLoc, diag::warn_bool_switch_condition)
481 << CondExpr->getSourceRange();
482 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000483 }
Sebastian Redlde307472009-01-11 00:38:46 +0000484
Chris Lattnerf4021e72007-08-23 05:46:52 +0000485 // Get the bitwidth of the switched-on value before promotions. We must
486 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000487 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000488 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000489 unsigned CondWidth
Douglas Gregordbb26db2009-05-15 23:57:33 +0000490 = HasDependentValue? 0
Chris Lattner5f048812009-10-16 16:45:22 +0000491 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
492 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattnerf4021e72007-08-23 05:46:52 +0000494 // Accumulate all of the case values in a vector so that we can sort them
495 // and detect duplicates. This vector contains the APInt for the case after
496 // it has been converted to the condition type.
Chris Lattner0471f5b2007-08-23 18:29:20 +0000497 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
498 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattnerf4021e72007-08-23 05:46:52 +0000500 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000501 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
502 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattnerf4021e72007-08-23 05:46:52 +0000504 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000506 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregordbb26db2009-05-15 23:57:33 +0000508 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000509 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000511 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000512 if (TheDefaultStmt) {
513 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000514 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000515
Chris Lattnerf4021e72007-08-23 05:46:52 +0000516 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000517 // we'll return a valid AST. This requires recursing down the AST and
518 // finding it, not something we are set up to do right now. For now,
519 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000520 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000521 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000522 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattnerf4021e72007-08-23 05:46:52 +0000524 } else {
525 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattnerf4021e72007-08-23 05:46:52 +0000527 // We already verified that the expression has a i-c-e value (C99
528 // 6.8.4.2p3) - get that value now.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000529 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000530
531 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
532 HasDependentValue = true;
533 break;
534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Anders Carlsson51fe9962008-11-22 21:04:56 +0000536 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattnerf4021e72007-08-23 05:46:52 +0000538 // Convert the value to the same width/sign as the condition.
539 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
540 CS->getLHS()->getLocStart(),
541 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000542
Chris Lattner1e0a3902008-01-16 19:17:22 +0000543 // If the LHS is not the same type as the condition, insert an implicit
544 // cast.
John McCall2de56d12010-08-25 11:45:40 +0000545 ImpCastExprToType(Lo, CondType, CK_IntegralCast);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000546 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000548 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000549 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000551 CS->getRHS()->isValueDependent()) {
552 HasDependentValue = true;
553 break;
554 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000555 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000556 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000557 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000558 }
559 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000560
561 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000562 // If we don't have a default statement, check whether the
563 // condition is constant.
564 llvm::APSInt ConstantCondValue;
565 bool HasConstantCond = false;
566 bool ShouldCheckConstantCond = false;
567 if (!HasDependentValue && !TheDefaultStmt) {
568 Expr::EvalResult Result;
569 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
570 if (HasConstantCond) {
571 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
572 ConstantCondValue = Result.Val.getInt();
573 ShouldCheckConstantCond = true;
574
575 assert(ConstantCondValue.getBitWidth() == CondWidth &&
576 ConstantCondValue.isSigned() == CondIsSigned);
577 }
578 }
579
Douglas Gregordbb26db2009-05-15 23:57:33 +0000580 // Sort all the scalar case values so we can easily detect duplicates.
581 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
582
583 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000584 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
585 if (ShouldCheckConstantCond &&
586 CaseVals[i].first == ConstantCondValue)
587 ShouldCheckConstantCond = false;
588
589 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000590 // If we have a duplicate, report it.
Mike Stump1eb44332009-09-09 15:08:12 +0000591 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCall0fb97082010-05-18 03:19:21 +0000592 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
593 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000594 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000595 // FIXME: We really want to remove the bogus case stmt from the
596 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000597 CaseListIsErroneous = true;
598 }
599 }
600 }
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregordbb26db2009-05-15 23:57:33 +0000602 // Detect duplicate case ranges, which usually don't exist at all in
603 // the first place.
604 if (!CaseRanges.empty()) {
605 // Sort all the case ranges by their low value so we can easily detect
606 // overlaps between ranges.
607 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Douglas Gregordbb26db2009-05-15 23:57:33 +0000609 // Scan the ranges, computing the high values and removing empty ranges.
610 std::vector<llvm::APSInt> HiVals;
611 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000612 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000613 CaseStmt *CR = CaseRanges[i].second;
614 Expr *Hi = CR->getRHS();
615 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Douglas Gregordbb26db2009-05-15 23:57:33 +0000617 // Convert the value to the same width/sign as the condition.
618 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
619 CR->getRHS()->getLocStart(),
620 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregordbb26db2009-05-15 23:57:33 +0000622 // If the LHS is not the same type as the condition, insert an implicit
623 // cast.
John McCall2de56d12010-08-25 11:45:40 +0000624 ImpCastExprToType(Hi, CondType, CK_IntegralCast);
Douglas Gregordbb26db2009-05-15 23:57:33 +0000625 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Douglas Gregordbb26db2009-05-15 23:57:33 +0000627 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000628 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000629 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
630 << SourceRange(CR->getLHS()->getLocStart(),
631 CR->getRHS()->getLocEnd());
632 CaseRanges.erase(CaseRanges.begin()+i);
633 --i, --e;
634 continue;
635 }
John McCall0fb97082010-05-18 03:19:21 +0000636
637 if (ShouldCheckConstantCond &&
638 LoVal <= ConstantCondValue &&
639 ConstantCondValue <= HiVal)
640 ShouldCheckConstantCond = false;
641
Douglas Gregordbb26db2009-05-15 23:57:33 +0000642 HiVals.push_back(HiVal);
643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Douglas Gregordbb26db2009-05-15 23:57:33 +0000645 // Rescan the ranges, looking for overlap with singleton values and other
646 // ranges. Since the range list is sorted, we only need to compare case
647 // ranges with their neighbors.
648 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
649 llvm::APSInt &CRLo = CaseRanges[i].first;
650 llvm::APSInt &CRHi = HiVals[i];
651 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Douglas Gregordbb26db2009-05-15 23:57:33 +0000653 // Check to see whether the case range overlaps with any
654 // singleton cases.
655 CaseStmt *OverlapStmt = 0;
656 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Douglas Gregordbb26db2009-05-15 23:57:33 +0000658 // Find the smallest value >= the lower bound. If I is in the
659 // case range, then we have overlap.
660 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
661 CaseVals.end(), CRLo,
662 CaseCompareFunctor());
663 if (I != CaseVals.end() && I->first < CRHi) {
664 OverlapVal = I->first; // Found overlap with scalar.
665 OverlapStmt = I->second;
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Douglas Gregordbb26db2009-05-15 23:57:33 +0000668 // Find the smallest value bigger than the upper bound.
669 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
670 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
671 OverlapVal = (I-1)->first; // Found overlap with scalar.
672 OverlapStmt = (I-1)->second;
673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Douglas Gregordbb26db2009-05-15 23:57:33 +0000675 // Check to see if this case stmt overlaps with the subsequent
676 // case range.
677 if (i && CRLo <= HiVals[i-1]) {
678 OverlapVal = HiVals[i-1]; // Found overlap with range.
679 OverlapStmt = CaseRanges[i-1].second;
680 }
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Douglas Gregordbb26db2009-05-15 23:57:33 +0000682 if (OverlapStmt) {
683 // If we have a duplicate, report it.
684 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
685 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000686 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000687 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000688 // FIXME: We really want to remove the bogus case stmt from the
689 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000690 CaseListIsErroneous = true;
691 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000692 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000693 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000694
John McCall0fb97082010-05-18 03:19:21 +0000695 // Complain if we have a constant condition and we didn't find a match.
696 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
697 // TODO: it would be nice if we printed enums as enums, chars as
698 // chars, etc.
699 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
700 << ConstantCondValue.toString(10)
701 << CondExpr->getSourceRange();
702 }
703
704 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000705 // values. We only issue a warning if there is not 'default:', but
706 // we still do the analysis to preserve this information in the AST
707 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000708 //
Chris Lattnerce784612010-09-16 17:09:42 +0000709 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000710
Douglas Gregorba915af2010-02-08 22:24:16 +0000711 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000712 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000713 const EnumDecl *ED = ET->getDecl();
714 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
715 EnumValsTy EnumVals;
716
John McCall0fb97082010-05-18 03:19:21 +0000717 // Gather all enum values, set their type and sort them,
718 // allowing easier comparison with CaseVals.
719 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
720 EDI != ED->enumerator_end(); EDI++) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000721 llvm::APSInt Val = (*EDI)->getInitVal();
722 if(Val.getBitWidth() < CondWidth)
723 Val.extend(CondWidth);
Douglas Gregor66235842010-06-29 17:12:35 +0000724 else if (Val.getBitWidth() > CondWidth)
725 Val.trunc(CondWidth);
Douglas Gregorba915af2010-02-08 22:24:16 +0000726 Val.setIsSigned(CondIsSigned);
727 EnumVals.push_back(std::make_pair(Val, (*EDI)));
728 }
729 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000730 EnumValsTy::iterator EIend =
731 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000732
733 // See which case values aren't in enum.
734 // TODO: we might want to check whether case values are out of the
735 // enum even if we don't want to check whether all cases are handled.
736 if (!TheDefaultStmt) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000737 EnumValsTy::const_iterator EI = EnumVals.begin();
738 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCall0fb97082010-05-18 03:19:21 +0000739 CI != CaseVals.end(); CI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000740 while (EI != EIend && EI->first < CI->first)
741 EI++;
742 if (EI == EIend || EI->first > CI->first)
John McCall0fb97082010-05-18 03:19:21 +0000743 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
744 << ED->getDeclName();
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000745 }
746 // See which of case ranges aren't in enum
747 EI = EnumVals.begin();
748 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCall0fb97082010-05-18 03:19:21 +0000749 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000750 while (EI != EIend && EI->first < RI->first)
751 EI++;
Douglas Gregorba915af2010-02-08 22:24:16 +0000752
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000753 if (EI == EIend || EI->first != RI->first) {
754 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
755 << ED->getDeclName();
756 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000757
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000758 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
759 while (EI != EIend && EI->first < Hi)
760 EI++;
761 if (EI == EIend || EI->first != Hi)
762 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
763 << ED->getDeclName();
764 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000765 }
Chris Lattnerce784612010-09-16 17:09:42 +0000766
Ted Kremenek559fb552010-09-09 00:05:53 +0000767 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000768 CaseValsTy::const_iterator CI = CaseVals.begin();
769 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000770 bool hasCasesNotInSwitch = false;
771
Chris Lattnerce784612010-09-16 17:09:42 +0000772 llvm::SmallVector<DeclarationName,8> UnhandledNames;
773
Ted Kremenek559fb552010-09-09 00:05:53 +0000774 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000775 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000776 llvm::APSInt CIVal;
777 while (CI != CaseVals.end() && CI->first < EI->first)
778 CI++;
779
780 if (CI != CaseVals.end() && CI->first == EI->first)
781 continue;
782
Ted Kremenek559fb552010-09-09 00:05:53 +0000783 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +0000784 for (; RI != CaseRanges.end(); RI++) {
785 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
786 if (EI->first <= Hi)
787 break;
788 }
789
Ted Kremenek559fb552010-09-09 00:05:53 +0000790 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000791 hasCasesNotInSwitch = true;
792 if (!TheDefaultStmt)
Chris Lattnerce784612010-09-16 17:09:42 +0000793 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000794 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000795 }
Chris Lattnerce784612010-09-16 17:09:42 +0000796
797 // Produce a nice diagnostic if multiple values aren't handled.
798 switch (UnhandledNames.size()) {
799 case 0: break;
800 case 1:
801 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
802 << UnhandledNames[0];
803 break;
804 case 2:
805 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
806 << UnhandledNames[0] << UnhandledNames[1];
807 break;
808 case 3:
809 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
810 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
811 break;
812 default:
813 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
814 << (unsigned)UnhandledNames.size()
815 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
816 break;
817 }
Ted Kremenek559fb552010-09-09 00:05:53 +0000818
819 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000820 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +0000821 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000822 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000823
Mike Stump390b4cc2009-05-16 07:39:55 +0000824 // FIXME: If the case list was broken is some way, we don't have a good system
825 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000826 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +0000827 return StmtError();
828
Sebastian Redlde307472009-01-11 00:38:46 +0000829 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
John McCall60d7b3a2010-08-24 06:29:42 +0000832StmtResult
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000833Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +0000834 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +0000835 ExprResult CondResult(Cond.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000836
Douglas Gregor5656e142009-11-24 21:15:44 +0000837 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000838 if (CondVar) {
839 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000840 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000841 if (CondResult.isInvalid())
842 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +0000843 }
John McCall9ae2f072010-08-23 23:25:46 +0000844 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000845 if (!ConditionExpr)
846 return StmtError();
847
John McCall9ae2f072010-08-23 23:25:46 +0000848 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000850 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +0000851 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000852}
853
John McCall60d7b3a2010-08-24 06:29:42 +0000854StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000855Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +0000856 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +0000857 Expr *Cond, SourceLocation CondRParen) {
858 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +0000859
John McCall9ae2f072010-08-23 23:25:46 +0000860 if (CheckBooleanCondition(Cond, DoLoc))
John McCall5a881bb2009-10-12 21:59:07 +0000861 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000862
John McCall60d7b3a2010-08-24 06:29:42 +0000863 ExprResult CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000864 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000865 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000866 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000867
John McCall9ae2f072010-08-23 23:25:46 +0000868 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +0000869
John McCall9ae2f072010-08-23 23:25:46 +0000870 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +0000871}
872
John McCall60d7b3a2010-08-24 06:29:42 +0000873StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +0000874Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000875 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000876 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +0000877 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000878 if (!getLangOptions().CPlusPlus) {
879 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000880 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
881 // declare identifiers for objects having storage class 'auto' or
882 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000883 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
884 DI!=DE; ++DI) {
885 VarDecl *VD = dyn_cast<VarDecl>(*DI);
886 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
887 VD = 0;
888 if (VD == 0)
889 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
890 // FIXME: mark decl erroneous!
891 }
Chris Lattnerae3b7012007-08-28 05:03:08 +0000892 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000894
John McCall60d7b3a2010-08-24 06:29:42 +0000895 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000896 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000897 if (secondVar) {
898 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000899 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000900 if (SecondResult.isInvalid())
901 return StmtError();
902 }
903
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000904 Expr *Third = third.release().takeAs<Expr>();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000905
Anders Carlsson3af708f2009-08-01 01:39:59 +0000906 DiagnoseUnusedExprResult(First);
907 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +0000908 DiagnoseUnusedExprResult(Body);
909
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000910 return Owned(new (Context) ForStmt(Context, First,
John McCall9ae2f072010-08-23 23:25:46 +0000911 SecondResult.take(), ConditionVar,
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000912 Third, Body, ForLoc, LParenLoc,
913 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000914}
915
John McCall60d7b3a2010-08-24 06:29:42 +0000916StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +0000917Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
918 SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000919 Stmt *First, Expr *Second,
920 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian20552d22008-01-10 20:33:58 +0000921 if (First) {
922 QualType FirstType;
923 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +0000924 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000925 return StmtError(Diag((*DS->decl_begin())->getLocation(),
926 diag::err_toomany_element_decls));
927
Chris Lattner7e24e822009-03-28 06:33:19 +0000928 Decl *D = DS->getSingleDecl();
Ted Kremenekf34afee2008-10-06 20:58:11 +0000929 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000930 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
931 // declare identifiers for objects having storage class 'auto' or
932 // 'register'.
Steve Naroff248a7532008-04-15 22:42:06 +0000933 VarDecl *VD = cast<VarDecl>(D);
934 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000935 return StmtError(Diag(VD->getLocation(),
936 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000937 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +0000938 Expr *FirstE = cast<Expr>(First);
939 if (!FirstE->isTypeDependent() &&
940 FirstE->isLvalue(Context) != Expr::LV_Valid)
Sebastian Redlf05b1522009-01-16 23:28:06 +0000941 return StmtError(Diag(First->getLocStart(),
942 diag::err_selector_element_not_lvalue)
943 << First->getSourceRange());
944
Mike Stump1eb44332009-09-09 15:08:12 +0000945 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000946 }
Douglas Gregorc3203e72010-04-22 23:10:45 +0000947 if (!FirstType->isDependentType() &&
948 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +0000949 !FirstType->isBlockPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000950 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000951 << FirstType << First->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000952 }
Douglas Gregorc3203e72010-04-22 23:10:45 +0000953 if (Second && !Second->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +0000954 DefaultFunctionArrayLvalueConversion(Second);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000955 QualType SecondType = Second->getType();
Steve Narofff4954562009-07-16 15:41:00 +0000956 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000957 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000958 << SecondType << Second->getSourceRange();
Fariborz Jahanianea161102010-08-12 22:25:42 +0000959 else if (const ObjCObjectPointerType *OPT =
960 SecondType->getAsObjCInterfacePointerType()) {
961 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
962 IdentifierInfo* selIdent =
963 &Context.Idents.get("countByEnumeratingWithState");
964 KeyIdents.push_back(selIdent);
965 selIdent = &Context.Idents.get("objects");
966 KeyIdents.push_back(selIdent);
967 selIdent = &Context.Idents.get("count");
968 KeyIdents.push_back(selIdent);
969 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
970 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
971 if (!IDecl->isForwardDecl() &&
972 !IDecl->lookupInstanceMethod(CSelector)) {
Fariborz Jahanian80a785c2010-08-12 22:33:42 +0000973 // Must further look into private implementation methods.
Fariborz Jahanianea161102010-08-12 22:25:42 +0000974 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
975 Diag(ForLoc, diag::warn_collection_expr_type)
976 << SecondType << CSelector << Second->getSourceRange();
977 }
978 }
979 }
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000980 }
Ted Kremenek8189cde2009-02-07 01:47:29 +0000981 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
982 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000983}
Reid Spencer5f016e22007-07-11 17:01:13 +0000984
John McCall60d7b3a2010-08-24 06:29:42 +0000985StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000986Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 IdentifierInfo *LabelII) {
988 // Look up the record for this label identifier.
John McCall781472f2010-08-25 08:40:02 +0000989 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
Reid Spencer5f016e22007-07-11 17:01:13 +0000990
John McCall781472f2010-08-25 08:40:02 +0000991 getCurFunction()->setHasBranchIntoScope();
John McCallb60a77e2010-08-01 00:26:45 +0000992
Steve Naroffcaaacec2009-03-13 15:38:40 +0000993 // If we haven't seen this label yet, create a forward reference.
994 if (LabelDecl == 0)
Ted Kremenek8189cde2009-02-07 01:47:29 +0000995 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000996
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +0000997 LabelDecl->setUsed();
Ted Kremenek8189cde2009-02-07 01:47:29 +0000998 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000999}
1000
John McCall60d7b3a2010-08-24 06:29:42 +00001001StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00001002Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001003 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00001004 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001005 if (!E->isTypeDependent()) {
1006 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00001007 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001008 AssignConvertType ConvTy =
Chandler Carruth28779982010-01-31 10:26:25 +00001009 CheckSingleAssignmentConstraints(DestTy, E);
1010 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001011 return StmtError();
1012 }
John McCallb60a77e2010-08-01 00:26:45 +00001013
John McCall781472f2010-08-25 08:40:02 +00001014 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00001015
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001016 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001017}
1018
John McCall60d7b3a2010-08-24 06:29:42 +00001019StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001020Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 Scope *S = CurScope->getContinueParent();
1022 if (!S) {
1023 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001024 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001026
Ted Kremenek8189cde2009-02-07 01:47:29 +00001027 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001028}
1029
John McCall60d7b3a2010-08-24 06:29:42 +00001030StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001031Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 Scope *S = CurScope->getBreakParent();
1033 if (!S) {
1034 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001035 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001037
Ted Kremenek8189cde2009-02-07 01:47:29 +00001038 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001039}
1040
Douglas Gregor5077c382010-05-15 06:01:05 +00001041/// \brief Determine whether a return statement is a candidate for the named
1042/// return value optimization (C++0x 12.8p34, bullet 1).
1043///
1044/// \param Ctx The context in which the return expression and type occur.
1045///
1046/// \param RetType The return type of the function or block.
1047///
1048/// \param RetExpr The expression being returned from the function or block.
1049///
1050/// \returns The NRVO candidate variable, if the return statement may use the
1051/// NRVO, or NULL if there is no such candidate.
1052static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1053 Expr *RetExpr) {
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001054 QualType ExprType = RetExpr->getType();
1055 // - in a return statement in a function with ...
1056 // ... a class return type ...
1057 if (!RetType->isRecordType())
Douglas Gregor5077c382010-05-15 06:01:05 +00001058 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001059 // ... the same cv-unqualified type as the function return type ...
1060 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
Douglas Gregor5077c382010-05-15 06:01:05 +00001061 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001062 // ... the expression is the name of a non-volatile automatic object ...
1063 // We ignore parentheses here.
1064 // FIXME: Is this compliant? (Everyone else does it)
1065 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1066 if (!DR)
Douglas Gregor5077c382010-05-15 06:01:05 +00001067 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001068 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1069 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00001070 return 0;
1071
1072 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
Douglas Gregord86c4772010-05-15 06:46:45 +00001073 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1074 !VD->getType().isVolatileQualified())
Douglas Gregor5077c382010-05-15 06:01:05 +00001075 return VD;
1076
1077 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001078}
1079
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001080/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001081///
John McCall60d7b3a2010-08-24 06:29:42 +00001082StmtResult
Steve Naroff4eb206b2008-09-03 18:15:37 +00001083Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00001084 // If this is the first return we've seen in the block, infer the type of
1085 // the block from it.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001086 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001087 if (CurBlock->ReturnType.isNull()) {
Steve Naroffc50a4a52008-09-16 22:25:10 +00001088 if (RetValExp) {
Steve Naroff16564422008-09-24 22:26:48 +00001089 // Don't call UsualUnaryConversions(), since we don't want to do
1090 // integer promotions here.
Douglas Gregora873dfc2010-02-03 00:27:59 +00001091 DefaultFunctionArrayLvalueConversion(RetValExp);
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001092 CurBlock->ReturnType = RetValExp->getType();
1093 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1094 // We have to remove a 'const' added to copied-in variable which was
1095 // part of the implementation spec. and not the actual qualifier for
1096 // the variable.
1097 if (CDRE->isConstQualAdded())
1098 CurBlock->ReturnType.removeConst();
1099 }
Steve Naroffc50a4a52008-09-16 22:25:10 +00001100 } else
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001101 CurBlock->ReturnType = Context.VoidTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00001102 }
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001103 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001104
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001105 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
Mike Stump6c92fa72009-04-29 21:40:37 +00001106 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1107 << getCurFunctionOrMethodDecl()->getDeclName();
1108 return StmtError();
1109 }
1110
Steve Naroff4eb206b2008-09-03 18:15:37 +00001111 // Otherwise, verify that this result type matches the previous one. We are
1112 // pickier with blocks than for normal functions because we don't have GCC
1113 // compatibility to worry about here.
Douglas Gregor5077c382010-05-15 06:01:05 +00001114 ReturnStmt *Result = 0;
Steve Naroff4eb206b2008-09-03 18:15:37 +00001115 if (CurBlock->ReturnType->isVoidType()) {
1116 if (RetValExp) {
1117 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001118 RetValExp = 0;
1119 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001120 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1121 } else if (!RetValExp) {
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001122 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor5077c382010-05-15 06:01:05 +00001123 } else {
1124 const VarDecl *NRVOCandidate = 0;
1125
1126 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1127 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001128
Douglas Gregor5077c382010-05-15 06:01:05 +00001129 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1130 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1131 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001132
Douglas Gregor5077c382010-05-15 06:01:05 +00001133 // In C++ the return statement is handled via a copy initialization.
1134 // the C version of which boils down to CheckSingleAssignmentConstraints.
1135 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
John McCall60d7b3a2010-08-24 06:29:42 +00001136 ExprResult Res = PerformCopyInitialization(
Douglas Gregor5077c382010-05-15 06:01:05 +00001137 InitializedEntity::InitializeResult(ReturnLoc,
1138 FnRetType,
1139 NRVOCandidate != 0),
1140 SourceLocation(),
1141 Owned(RetValExp));
1142 if (Res.isInvalid()) {
1143 // FIXME: Cleanup temporaries here, anyway?
1144 return StmtError();
1145 }
1146
1147 if (RetValExp)
1148 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
Mike Stump98eb8a72009-02-04 22:31:32 +00001149
Douglas Gregor5077c382010-05-15 06:01:05 +00001150 RetValExp = Res.takeAs<Expr>();
1151 if (RetValExp)
1152 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlssonc6acbc52010-01-29 18:30:20 +00001153 }
1154
Douglas Gregor5077c382010-05-15 06:01:05 +00001155 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001156 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001157
Douglas Gregor5077c382010-05-15 06:01:05 +00001158 // If we need to check for the named return value optimization, save the
1159 // return statement in our scope for later processing.
1160 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1161 !CurContext->isDependentContext())
1162 FunctionScopes.back()->Returns.push_back(Result);
1163
1164 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001165}
Reid Spencer5f016e22007-07-11 17:01:13 +00001166
John McCall60d7b3a2010-08-24 06:29:42 +00001167StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001168Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001169 if (getCurBlock())
Steve Naroff4eb206b2008-09-03 18:15:37 +00001170 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001171
Chris Lattner371f2582008-12-04 23:50:19 +00001172 QualType FnRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00001173 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00001174 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00001175 if (FD->hasAttr<NoReturnAttr>() ||
1176 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00001177 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpf7c41da2009-04-29 00:43:21 +00001178 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpf7c41da2009-04-29 00:43:21 +00001179 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Naroffc97fb9a2009-03-03 00:45:38 +00001180 FnRetType = MD->getResultType();
1181 else // If we don't have a function/method context, bail.
1182 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregor5077c382010-05-15 06:01:05 +00001184 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00001185 if (FnRetType->isVoidType()) {
Douglas Gregor1be8aee2009-10-01 23:25:31 +00001186 if (RetValExp && !RetValExp->isTypeDependent()) {
1187 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner65ce04b2008-12-18 02:01:17 +00001188 unsigned D = diag::ext_return_has_expr;
1189 if (RetValExp->getType()->isVoidType())
1190 D = diag::ext_return_has_void_expr;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001191
Chris Lattnere878eb02008-12-18 02:03:48 +00001192 // return (some void expression); is legal in C++.
1193 if (D != diag::ext_return_has_void_expr ||
1194 !getLangOptions().CPlusPlus) {
1195 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1196 Diag(ReturnLoc, D)
1197 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1198 << RetValExp->getSourceRange();
1199 }
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Anders Carlsson0ece4912009-12-15 20:51:39 +00001201 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001203
1204 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1205 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001206 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1207 // C99 6.8.6.4p1 (ext_ since GCC warns)
1208 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1209
1210 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00001211 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00001212 else
Chris Lattner08631c52008-11-23 21:45:46 +00001213 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00001214 Result = new (Context) ReturnStmt(ReturnLoc);
1215 } else {
1216 const VarDecl *NRVOCandidate = 0;
1217 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1218 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001219
Douglas Gregor5077c382010-05-15 06:01:05 +00001220 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1221 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1222 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001223
Douglas Gregor5077c382010-05-15 06:01:05 +00001224 // In C++ the return statement is handled via a copy initialization.
1225 // the C version of which boils down to CheckSingleAssignmentConstraints.
1226 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
John McCall60d7b3a2010-08-24 06:29:42 +00001227 ExprResult Res = PerformCopyInitialization(
Douglas Gregor5077c382010-05-15 06:01:05 +00001228 InitializedEntity::InitializeResult(ReturnLoc,
1229 FnRetType,
1230 NRVOCandidate != 0),
1231 SourceLocation(),
1232 Owned(RetValExp));
1233 if (Res.isInvalid()) {
1234 // FIXME: Cleanup temporaries here, anyway?
1235 return StmtError();
1236 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001237
Douglas Gregor5077c382010-05-15 06:01:05 +00001238 RetValExp = Res.takeAs<Expr>();
1239 if (RetValExp)
1240 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001241 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001242
1243 if (RetValExp)
1244 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1245 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00001246 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001247
1248 // If we need to check for the named return value optimization, save the
1249 // return statement in our scope for later processing.
1250 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1251 !CurContext->isDependentContext())
1252 FunctionScopes.back()->Returns.push_back(Result);
1253
1254 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001255}
1256
Chris Lattner810f6d52009-03-13 17:38:01 +00001257/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1258/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1259/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1260/// provide a strong guidance to not use it.
1261///
1262/// This method checks to see if the argument is an acceptable l-value and
1263/// returns false if it is a case we can handle.
1264static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00001265 // Type dependent expressions will be checked during instantiation.
1266 if (E->isTypeDependent())
1267 return false;
1268
Chris Lattner810f6d52009-03-13 17:38:01 +00001269 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1270 return false; // Cool, this is an lvalue.
1271
1272 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1273 // are supposed to allow.
1274 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1275 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1276 if (!S.getLangOptions().HeinousExtensions)
1277 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1278 << E->getSourceRange();
1279 else
1280 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1281 << E->getSourceRange();
1282 // Accept, even if we emitted an error diagnostic.
1283 return false;
1284 }
1285
1286 // None of the above, just randomly invalid non-lvalue.
1287 return true;
1288}
1289
1290
John McCall60d7b3a2010-08-24 06:29:42 +00001291StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001292 bool IsSimple,
1293 bool IsVolatile,
1294 unsigned NumOutputs,
1295 unsigned NumInputs,
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001296 IdentifierInfo **Names,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001297 MultiExprArg constraints,
1298 MultiExprArg exprs,
John McCall9ae2f072010-08-23 23:25:46 +00001299 Expr *asmString,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001300 MultiExprArg clobbers,
Mike Stump3b11fd32010-01-04 22:37:17 +00001301 SourceLocation RParenLoc,
1302 bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00001303 unsigned NumClobbers = clobbers.size();
1304 StringLiteral **Constraints =
1305 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00001306 Expr **Exprs = exprs.get();
1307 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00001308 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1309
Anders Carlsson03eb5432009-01-27 20:38:24 +00001310 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Chris Lattner1708b962008-08-18 19:55:17 +00001312 // The parser verifies that there is a string literal here.
Chris Lattner6bc52112008-07-23 06:46:56 +00001313 if (AsmString->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001314 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1315 << AsmString->getSourceRange());
1316
Chris Lattner1708b962008-08-18 19:55:17 +00001317 for (unsigned i = 0; i != NumOutputs; i++) {
1318 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001319 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001320 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1321 << Literal->getSourceRange());
1322
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001323 llvm::StringRef OutputName;
1324 if (Names[i])
1325 OutputName = Names[i]->getName();
1326
1327 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattner432c8692009-04-26 17:19:08 +00001328 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001329 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001330 diag::err_asm_invalid_output_constraint)
1331 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00001332
Anders Carlssond04c6e22007-11-27 04:11:28 +00001333 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00001334 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00001335 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00001336 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001337 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00001338 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001339 }
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Chris Lattner44def072009-04-26 07:16:29 +00001341 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001342 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001343
Chris Lattner806503f2009-05-03 05:55:43 +00001344 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1345
Anders Carlsson04728b72007-11-23 19:43:50 +00001346 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00001347 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001348 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001349 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1350 << Literal->getSourceRange());
1351
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001352 llvm::StringRef InputName;
1353 if (Names[i])
1354 InputName = Names[i]->getName();
1355
1356 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foadbeaaccd2009-05-21 09:52:38 +00001357 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001358 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00001359 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001360 diag::err_asm_invalid_input_constraint)
1361 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00001362 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001363
Eli Friedman72056a22009-05-03 07:49:42 +00001364 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00001365
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001366 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00001367 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00001368 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00001369 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001370 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00001371 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001372 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001373 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001374
Chris Lattner44def072009-04-26 07:16:29 +00001375 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001376 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00001377 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001378 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00001379 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001380 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001381 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Douglas Gregora873dfc2010-02-03 00:27:59 +00001384 DefaultFunctionArrayLvalueConversion(Exprs[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Chris Lattner806503f2009-05-03 05:55:43 +00001386 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001387 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001388
Anders Carlsson6fa90862007-11-25 00:25:21 +00001389 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00001390 for (unsigned i = 0; i != NumClobbers; i++) {
1391 StringLiteral *Literal = Clobbers[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001392 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001393 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1394 << Literal->getSourceRange());
1395
Anders Carlssonfdba9c02010-01-30 19:34:25 +00001396 llvm::StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00001397
Anders Carlssonfdba9c02010-01-30 19:34:25 +00001398 if (!Context.Target.isValidGCCRegisterName(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001399 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00001400 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00001401 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001402
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001403 AsmStmt *NS =
Anders Carlsson966146e2010-01-30 23:19:41 +00001404 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1405 NumOutputs, NumInputs, Names, Constraints, Exprs,
1406 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001407 // Validate the asm string, ensuring it makes sense given the operands we
1408 // have.
1409 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1410 unsigned DiagOffs;
1411 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00001412 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1413 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001414 return StmtError();
1415 }
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner806503f2009-05-03 05:55:43 +00001417 // Validate tied input operands for type mismatches.
1418 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1419 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Chris Lattner806503f2009-05-03 05:55:43 +00001421 // If this is a tied constraint, verify that the output and input have
1422 // either exactly the same type, or that they are int/ptr operands with the
1423 // same size (int/long, int*/long, are ok etc).
1424 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Chris Lattner806503f2009-05-03 05:55:43 +00001426 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001427 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001428 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner7adaa182009-05-03 05:59:17 +00001429 QualType InTy = InputExpr->getType();
1430 QualType OutTy = OutputExpr->getType();
1431 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00001432 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Chris Lattneraab64d02010-04-23 17:27:29 +00001434 // Decide if the input and output are in the same domain (integer/ptr or
1435 // floating point.
1436 enum AsmDomain {
1437 AD_Int, AD_FP, AD_Other
1438 } InputDomain, OutputDomain;
1439
1440 if (InTy->isIntegerType() || InTy->isPointerType())
1441 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001442 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00001443 InputDomain = AD_FP;
1444 else
1445 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattneraab64d02010-04-23 17:27:29 +00001447 if (OutTy->isIntegerType() || OutTy->isPointerType())
1448 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001449 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00001450 OutputDomain = AD_FP;
1451 else
1452 OutputDomain = AD_Other;
1453
1454 // They are ok if they are the same size and in the same domain. This
1455 // allows tying things like:
1456 // void* to int*
1457 // void* to int if they are the same size.
1458 // double to long double if they are the same size.
1459 //
1460 uint64_t OutSize = Context.getTypeSize(OutTy);
1461 uint64_t InSize = Context.getTypeSize(InTy);
1462 if (OutSize == InSize && InputDomain == OutputDomain &&
1463 InputDomain != AD_Other)
1464 continue;
1465
1466 // If the smaller input/output operand is not mentioned in the asm string,
1467 // then we can promote it and the asm string won't notice. Check this
1468 // case now.
1469 bool SmallerValueMentioned = false;
1470 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1471 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1472 if (!Piece.isOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Chris Lattneraab64d02010-04-23 17:27:29 +00001474 // If this is a reference to the input and if the input was the smaller
1475 // one, then we have to reject this asm.
1476 if (Piece.getOperandNo() == i+NumOutputs) {
1477 if (InSize < OutSize) {
1478 SmallerValueMentioned = true;
1479 break;
Chris Lattner3351f112009-05-03 08:32:32 +00001480 }
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattneraab64d02010-04-23 17:27:29 +00001483 // If this is a reference to the input and if the input was the smaller
1484 // one, then we have to reject this asm.
1485 if (Piece.getOperandNo() == TiedTo) {
1486 if (InSize > OutSize) {
1487 SmallerValueMentioned = true;
1488 break;
1489 }
1490 }
Chris Lattner806503f2009-05-03 05:55:43 +00001491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Chris Lattneraab64d02010-04-23 17:27:29 +00001493 // If the smaller value wasn't mentioned in the asm string, and if the
1494 // output was a register, just extend the shorter one to the size of the
1495 // larger one.
1496 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1497 OutputConstraintInfos[TiedTo].allowsRegister())
1498 continue;
1499
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001500 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00001501 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00001502 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00001503 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00001504 return StmtError();
1505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001507 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00001508}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001509
John McCall60d7b3a2010-08-24 06:29:42 +00001510StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00001511Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00001512 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00001513 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00001514 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00001515 if (Var && Var->isInvalidDecl())
1516 return StmtError();
1517
John McCall9ae2f072010-08-23 23:25:46 +00001518 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001519}
1520
John McCall60d7b3a2010-08-24 06:29:42 +00001521StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001522Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1523 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00001524}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001525
John McCall60d7b3a2010-08-24 06:29:42 +00001526StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001527Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1528 MultiStmtArg CatchStmts, Stmt *Finally) {
John McCall781472f2010-08-25 08:40:02 +00001529 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001530 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00001531 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1532 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001533 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00001534 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001535}
1536
John McCall60d7b3a2010-08-24 06:29:42 +00001537StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001538 Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00001539 if (Throw) {
1540 QualType ThrowType = Throw->getType();
1541 // Make sure the expression type is an ObjC pointer or "void *".
1542 if (!ThrowType->isDependentType() &&
1543 !ThrowType->isObjCObjectPointerType()) {
1544 const PointerType *PT = ThrowType->getAs<PointerType>();
1545 if (!PT || !PT->getPointeeType()->isVoidType())
1546 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1547 << Throw->getType() << Throw->getSourceRange());
1548 }
1549 }
1550
John McCall9ae2f072010-08-23 23:25:46 +00001551 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00001552}
1553
John McCall60d7b3a2010-08-24 06:29:42 +00001554StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001555Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00001556 Scope *CurScope) {
John McCall9ae2f072010-08-23 23:25:46 +00001557 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00001558 // @throw without an expression designates a rethrow (which much occur
1559 // in the context of an @catch clause).
1560 Scope *AtCatchParent = CurScope;
1561 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1562 AtCatchParent = AtCatchParent->getParent();
1563 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00001564 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
Douglas Gregord1377b22010-04-22 21:44:01 +00001565 }
1566
John McCall9ae2f072010-08-23 23:25:46 +00001567 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00001568}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001569
John McCall60d7b3a2010-08-24 06:29:42 +00001570StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001571Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1572 Stmt *SyncBody) {
John McCall781472f2010-08-25 08:40:02 +00001573 getCurFunction()->setHasBranchProtectedScope();
Chris Lattner46c3c4b2009-04-21 06:01:00 +00001574
Chris Lattnera868a202009-04-21 06:11:25 +00001575 // Make sure the expression type is an ObjC pointer or "void *".
Douglas Gregor8fdc13a2010-04-22 22:01:21 +00001576 if (!SyncExpr->getType()->isDependentType() &&
1577 !SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001578 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattnera868a202009-04-21 06:11:25 +00001579 if (!PT || !PT->getPointeeType()->isVoidType())
1580 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1581 << SyncExpr->getType() << SyncExpr->getSourceRange());
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
John McCall9ae2f072010-08-23 23:25:46 +00001584 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00001585}
Sebastian Redl4b07b292008-12-22 19:15:10 +00001586
1587/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1588/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00001589StmtResult
John McCalld226f652010-08-21 09:40:31 +00001590Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00001591 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00001592 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001593 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00001594 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00001595 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00001596}
Sebastian Redl8351da02008-12-22 21:35:02 +00001597
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001598namespace {
1599
Sebastian Redlc447aba2009-07-29 17:15:45 +00001600class TypeWithHandler {
1601 QualType t;
1602 CXXCatchStmt *stmt;
1603public:
1604 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1605 : t(type), stmt(statement) {}
1606
John McCall0953e762009-09-24 19:53:00 +00001607 // An arbitrary order is fine as long as it places identical
1608 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00001609 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00001610 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00001611 return true;
John McCall0953e762009-09-24 19:53:00 +00001612 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00001613 return false;
1614 else
1615 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Sebastian Redlc447aba2009-07-29 17:15:45 +00001618 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00001619 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00001620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Sebastian Redlc447aba2009-07-29 17:15:45 +00001622 CXXCatchStmt *getCatchStmt() const { return stmt; }
1623 SourceLocation getTypeSpecStartLoc() const {
1624 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1625 }
1626};
1627
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001628}
1629
Sebastian Redl8351da02008-12-22 21:35:02 +00001630/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1631/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00001632StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001633Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00001634 MultiStmtArg RawHandlers) {
1635 unsigned NumHandlers = RawHandlers.size();
1636 assert(NumHandlers > 0 &&
1637 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00001638 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00001639
Sebastian Redlc447aba2009-07-29 17:15:45 +00001640 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
1642 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl8351da02008-12-22 21:35:02 +00001643 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00001644 if (!Handler->getExceptionDecl()) {
1645 if (i < NumHandlers - 1)
1646 return StmtError(Diag(Handler->getLocStart(),
1647 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Sebastian Redlc447aba2009-07-29 17:15:45 +00001649 continue;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Sebastian Redlc447aba2009-07-29 17:15:45 +00001652 const QualType CaughtType = Handler->getCaughtType();
1653 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1654 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00001655 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00001656
1657 // Detect handlers for the same type as an earlier one.
1658 if (NumHandlers > 1) {
1659 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Sebastian Redlc447aba2009-07-29 17:15:45 +00001661 TypeWithHandler prev = TypesWithHandlers[0];
1662 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1663 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Sebastian Redlc447aba2009-07-29 17:15:45 +00001665 if (curr == prev) {
1666 Diag(curr.getTypeSpecStartLoc(),
1667 diag::warn_exception_caught_by_earlier_handler)
1668 << curr.getCatchStmt()->getCaughtType().getAsString();
1669 Diag(prev.getTypeSpecStartLoc(),
1670 diag::note_previous_exception_handler)
1671 << prev.getCatchStmt()->getCaughtType().getAsString();
1672 }
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Sebastian Redlc447aba2009-07-29 17:15:45 +00001674 prev = curr;
1675 }
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
John McCall781472f2010-08-25 08:40:02 +00001678 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00001679
Sebastian Redl8351da02008-12-22 21:35:02 +00001680 // FIXME: We should detect handlers that cannot catch anything because an
1681 // earlier handler catches a superclass. Need to find a method that is not
1682 // quadratic for this.
1683 // Neither of these are explicitly forbidden, but every compiler detects them
1684 // and warns.
1685
John McCall9ae2f072010-08-23 23:25:46 +00001686 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00001687 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00001688}