blob: 61ab3d3a5bc98192d93bdbfede62ce0b975f662c [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();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000035 if (!E) // FIXME: FullExprArg has no error state?
36 return StmtError();
37
Chris Lattner834a72a2008-07-25 23:18:17 +000038 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
39 // void expression for its side effects. Conversion to void allows any
40 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000041
Chris Lattner834a72a2008-07-25 23:18:17 +000042 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000043 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000044}
45
46
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +000047StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) {
48 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000049}
50
Chris Lattner337e5502011-02-18 01:27:55 +000051StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
52 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000053 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner20401692009-04-12 20:13:14 +000055 // If we have an invalid decl, just return an error.
56 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000057
Chris Lattner24e1e702009-03-04 04:23:07 +000058 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000059}
60
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000061void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
62 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000063
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000064 // If we have an invalid decl, just return.
65 if (DG.isNull() || !DG.isSingleDecl()) return;
66 // suppress any potential 'unused variable' warning.
67 DG.getSingleDecl()->setUsed();
68}
69
Anders Carlsson636463e2009-07-30 22:17:18 +000070void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +000071 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
72 return DiagnoseUnusedExprResult(Label->getSubStmt());
73
Anders Carlsson75443112009-07-30 22:39:03 +000074 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +000075 if (!E)
76 return;
77
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000078 if (E->isBoundMemberFunction(Context)) {
79 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
80 << E->getSourceRange();
81 return;
82 }
83
Anders Carlsson636463e2009-07-30 22:17:18 +000084 SourceLocation Loc;
85 SourceRange R1, R2;
Mike Stumpdf317bf2009-11-03 23:25:48 +000086 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +000087 return;
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner419cfb32009-08-16 16:57:27 +000089 // Okay, we have an unused result. Depending on what the base expression is,
90 // we might want to make a more specific diagnostic. Check for one of these
91 // cases now.
92 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +000093 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +000094 E = Temps->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +000095
John McCallf6a16482010-12-04 03:47:34 +000096 E = E->IgnoreParenImpCasts();
Chris Lattnerbc8d42c2009-10-13 04:53:48 +000097 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +000098 if (E->getType()->isVoidType())
99 return;
100
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000101 // If the callee has attribute pure, const, or warn_unused_result, warn with
102 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000103 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000104 if (FD->getAttr<WarnUnusedResultAttr>()) {
105 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
106 return;
107 }
108 if (FD->getAttr<PureAttr>()) {
109 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
110 return;
111 }
112 if (FD->getAttr<ConstAttr>()) {
113 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
114 return;
115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000116 }
John McCall12f78a62010-12-02 01:19:52 +0000117 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000118 const ObjCMethodDecl *MD = ME->getMethodDecl();
119 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
120 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
121 return;
122 }
John McCall12f78a62010-12-02 01:19:52 +0000123 } else if (isa<ObjCPropertyRefExpr>(E)) {
124 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000125 } else if (const CXXFunctionalCastExpr *FC
126 = dyn_cast<CXXFunctionalCastExpr>(E)) {
127 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
128 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
129 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000130 }
John McCall209acbd2010-04-06 22:24:14 +0000131 // Diagnose "(void*) blah" as a typo for "(void) blah".
132 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
133 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
134 QualType T = TI->getType();
135
136 // We really do want to use the non-canonical type here.
137 if (T == Context.VoidPtrTy) {
138 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
139
140 Diag(Loc, diag::warn_unused_voidptr)
141 << FixItHint::CreateRemoval(TL.getStarLoc());
142 return;
143 }
144 }
145
Douglas Gregor35e12c92010-07-15 18:47:04 +0000146 DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000147}
148
John McCall60d7b3a2010-08-24 06:29:42 +0000149StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000150Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000151 MultiStmtArg elts, bool isStmtExpr) {
152 unsigned NumElts = elts.size();
153 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000154 // If we're in C89 mode, check that we don't have any decls after stmts. If
155 // so, emit an extension diagnostic.
156 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
157 // Note that __extension__ can be around a decl.
158 unsigned i = 0;
159 // Skip over all declarations.
160 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
161 /*empty*/;
162
163 // We found the end of the list or a statement. Scan for another declstmt.
164 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
165 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000167 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000168 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000169 Diag(D->getLocation(), diag::ext_mixed_decls_code);
170 }
171 }
Chris Lattner98414c12007-08-31 21:49:55 +0000172 // Warn about unused expressions in statements.
173 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000174 // Ignore statements that are last in a statement expression.
175 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000176 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson636463e2009-07-30 22:17:18 +0000178 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000179 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000180
Ted Kremenek8189cde2009-02-07 01:47:29 +0000181 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000182}
183
John McCall60d7b3a2010-08-24 06:29:42 +0000184StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000185Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
186 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000187 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000188 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000189
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000191 // However, GCC allows any evaluatable integer expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000192 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregordbb26db2009-05-15 23:57:33 +0000193 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner24e1e702009-03-04 04:23:07 +0000194 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000195
Chris Lattner6c36be52007-07-18 02:28:47 +0000196 // GCC extension: The expression shall be an integer constant.
Sebastian Redl117054a2008-12-28 16:13:43 +0000197
Douglas Gregordbb26db2009-05-15 23:57:33 +0000198 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
199 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000200 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl117054a2008-12-28 16:13:43 +0000201 }
202
John McCall781472f2010-08-25 08:40:02 +0000203 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000204 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000205 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000206 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000207
Douglas Gregordbb26db2009-05-15 23:57:33 +0000208 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
209 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000210 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000211 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000212}
213
Chris Lattner24e1e702009-03-04 04:23:07 +0000214/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000215void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chris Lattner24e1e702009-03-04 04:23:07 +0000216 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000217 CS->setSubStmt(SubStmt);
218}
219
John McCall60d7b3a2010-08-24 06:29:42 +0000220StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000221Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000222 Stmt *SubStmt, Scope *CurScope) {
John McCall781472f2010-08-25 08:40:02 +0000223 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000224 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000225 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000226 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000227
Douglas Gregordbb26db2009-05-15 23:57:33 +0000228 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000229 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000230 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000231}
232
John McCall60d7b3a2010-08-24 06:29:42 +0000233StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000234Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
235 SourceLocation ColonLoc, Stmt *SubStmt) {
236
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000237 // If the label was multiply defined, reject it now.
238 if (TheDecl->getStmt()) {
239 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
240 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000241 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 }
Sebastian Redlde307472009-01-11 00:38:46 +0000243
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000244 // Otherwise, things are good. Fill in the declaration and return it.
245 TheDecl->setLocation(IdentLoc);
246
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000247 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
248 TheDecl->setStmt(LS);
249 TheDecl->setLocation(IdentLoc);
250 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000251}
252
John McCall60d7b3a2010-08-24 06:29:42 +0000253StmtResult
John McCalld226f652010-08-21 09:40:31 +0000254Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000255 Stmt *thenStmt, SourceLocation ElseLoc,
256 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000257 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000259 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000260 if (CondVar) {
261 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000262 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000263 if (CondResult.isInvalid())
264 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000265 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000266 Expr *ConditionExpr = CondResult.takeAs<Expr>();
267 if (!ConditionExpr)
268 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000269
Anders Carlsson75443112009-07-30 22:39:03 +0000270 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000271
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000272 // Warn if the if block has a null body without an else value.
273 // this helps prevent bugs due to typos, such as
274 // if (condition);
275 // do_stuff();
Ted Kremenekb3198172010-09-16 00:37:05 +0000276 //
John McCall9ae2f072010-08-23 23:25:46 +0000277 if (!elseStmt) {
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000278 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidisa25b6a42010-11-19 20:54:25 +0000279 // But do not warn if the body is a macro that expands to nothing, e.g:
280 //
281 // #define CALL(x)
282 // if (condition)
283 // CALL(0);
284 //
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000285 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenekb3198172010-09-16 00:37:05 +0000286 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000287 }
288
Anders Carlsson75443112009-07-30 22:39:03 +0000289 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000290
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000291 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000292 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000293}
294
Chris Lattnerf4021e72007-08-23 05:46:52 +0000295/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
296/// the specified width and sign. If an overflow occurs, detect it and emit
297/// the specified diagnostic.
298void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
299 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000300 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000301 unsigned DiagID) {
302 // Perform a conversion to the promoted condition type if needed.
303 if (NewWidth > Val.getBitWidth()) {
304 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000305 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000306 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000307
308 // If the input was signed and negative and the output is
309 // unsigned, don't bother to warn: this is implementation-defined
310 // behavior.
311 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000312 } else if (NewWidth < Val.getBitWidth()) {
313 // If this is a truncation, check for overflow.
314 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000315 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000316 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000317 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000318 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000319 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000320 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattnerf4021e72007-08-23 05:46:52 +0000322 // Regardless of whether a diagnostic was emitted, really do the
323 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000324 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000325 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000326 } else if (NewSign != Val.isSigned()) {
327 // Convert the sign to match the sign of the condition. This can cause
328 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000330 // behavior.
331 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000332 llvm::APSInt OldVal(Val);
333 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000334 }
335}
336
Chris Lattner0471f5b2007-08-23 18:29:20 +0000337namespace {
338 struct CaseCompareFunctor {
339 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
340 const llvm::APSInt &RHS) {
341 return LHS.first < RHS;
342 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000343 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
344 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
345 return LHS.first < RHS.first;
346 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000347 bool operator()(const llvm::APSInt &LHS,
348 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
349 return LHS < RHS.first;
350 }
351 };
352}
353
Chris Lattner764a7ce2007-09-21 18:15:22 +0000354/// CmpCaseVals - Comparison predicate for sorting case values.
355///
356static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
357 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
358 if (lhs.first < rhs.first)
359 return true;
360
361 if (lhs.first == rhs.first &&
362 lhs.second->getCaseLoc().getRawEncoding()
363 < rhs.second->getCaseLoc().getRawEncoding())
364 return true;
365 return false;
366}
367
Douglas Gregorba915af2010-02-08 22:24:16 +0000368/// CmpEnumVals - Comparison predicate for sorting enumeration values.
369///
370static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
371 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
372{
373 return lhs.first < rhs.first;
374}
375
376/// EqEnumVals - Comparison preficate for uniqing enumeration values.
377///
378static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
379 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
380{
381 return lhs.first == rhs.first;
382}
383
Chris Lattner5f048812009-10-16 16:45:22 +0000384/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
385/// potentially integral-promoted expression @p expr.
386static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
John McCall6907fbe2010-06-12 01:56:02 +0000387 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
Chris Lattner5f048812009-10-16 16:45:22 +0000388 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
389 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000390 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
Chris Lattner5f048812009-10-16 16:45:22 +0000391 return TypeBeforePromotion;
392 }
393 }
394 return expr->getType();
395}
396
John McCall60d7b3a2010-08-24 06:29:42 +0000397StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000399 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000400 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000401
Douglas Gregor586596f2010-05-06 17:25:47 +0000402 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000403 if (CondVar) {
404 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000405 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
406 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000407 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408
John McCall9ae2f072010-08-23 23:25:46 +0000409 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000410 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
John McCall9ae2f072010-08-23 23:25:46 +0000412 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000413 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000414
John McCall9ae2f072010-08-23 23:25:46 +0000415 CondResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
Douglas Gregorc30614b2010-06-29 23:17:37 +0000417 PDiag(diag::err_typecheck_statement_requires_integer),
418 PDiag(diag::err_switch_incomplete_class_type)
John McCall9ae2f072010-08-23 23:25:46 +0000419 << Cond->getSourceRange(),
Douglas Gregorc30614b2010-06-29 23:17:37 +0000420 PDiag(diag::err_switch_explicit_conversion),
421 PDiag(diag::note_switch_conversion),
422 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000423 PDiag(diag::note_switch_conversion),
424 PDiag(0));
John McCall9ae2f072010-08-23 23:25:46 +0000425 if (CondResult.isInvalid()) return StmtError();
426 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427
John McCalld226f652010-08-21 09:40:31 +0000428 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000429 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000430 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000431 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000432 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000433 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000434 }
John McCallb60a77e2010-08-01 00:26:45 +0000435
John McCall781472f2010-08-25 08:40:02 +0000436 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000437
John McCall9ae2f072010-08-23 23:25:46 +0000438 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000439 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000440 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000441}
442
Gabor Greif28164ab2010-10-01 22:05:14 +0000443static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
444 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000445 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000446 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000447 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000448 Val.setIsSigned(IsSigned);
449}
450
John McCall60d7b3a2010-08-24 06:29:42 +0000451StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000452Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
453 Stmt *BodyStmt) {
454 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000455 assert(SS == getCurFunction()->SwitchStack.back() &&
456 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000457
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000458 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000459 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000460
Douglas Gregorff331c12010-07-25 18:17:45 +0000461 if (SS->getCond() == 0)
Douglas Gregorbe724ba2009-11-25 06:20:02 +0000462 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463
Chris Lattnerf4021e72007-08-23 05:46:52 +0000464 Expr *CondExpr = SS->getCond();
John McCall0fb97082010-05-18 03:19:21 +0000465 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000466 QualType CondTypeBeforePromotion =
467 GetTypeBeforeIntegralPromotion(CondExpr);
Sebastian Redlde307472009-01-11 00:38:46 +0000468
Douglas Gregor0de55e72009-11-25 15:17:36 +0000469 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
470 UsualUnaryConversions(CondExpr);
Douglas Gregora0d3ca12009-11-25 05:02:21 +0000471 QualType CondType = CondExpr->getType();
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000472 SS->setCond(CondExpr);
473
Chris Lattner5f048812009-10-16 16:45:22 +0000474 // C++ 6.4.2.p2:
475 // Integral promotions are performed (on the switch condition).
476 //
477 // A case value unrepresentable by the original switch condition
478 // type (before the promotion) doesn't make sense, even when it can
479 // be represented by the promoted type. Therefore we need to find
480 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000481 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000482 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000483 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000484 // appropriate type now, just return an error.
485 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000486 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000487
Chris Lattner2b334bb2010-04-16 23:34:13 +0000488 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000489 // switch(bool_expr) {...} is often a programmer error, e.g.
490 // switch(n && mask) { ... } // Doh - should be "n & mask".
491 // One can always use an if statement instead of switch(bool_expr).
492 Diag(SwitchLoc, diag::warn_bool_switch_condition)
493 << CondExpr->getSourceRange();
494 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000495 }
Sebastian Redlde307472009-01-11 00:38:46 +0000496
Chris Lattnerf4021e72007-08-23 05:46:52 +0000497 // Get the bitwidth of the switched-on value before promotions. We must
498 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000499 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000500 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000501 unsigned CondWidth
Douglas Gregordbb26db2009-05-15 23:57:33 +0000502 = HasDependentValue? 0
Chris Lattner5f048812009-10-16 16:45:22 +0000503 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
504 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattnerf4021e72007-08-23 05:46:52 +0000506 // Accumulate all of the case values in a vector so that we can sort them
507 // and detect duplicates. This vector contains the APInt for the case after
508 // it has been converted to the condition type.
Chris Lattner0471f5b2007-08-23 18:29:20 +0000509 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
510 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattnerf4021e72007-08-23 05:46:52 +0000512 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000513 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
514 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattnerf4021e72007-08-23 05:46:52 +0000516 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000518 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregordbb26db2009-05-15 23:57:33 +0000520 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000521 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000523 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000524 if (TheDefaultStmt) {
525 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000526 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000527
Chris Lattnerf4021e72007-08-23 05:46:52 +0000528 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000529 // we'll return a valid AST. This requires recursing down the AST and
530 // finding it, not something we are set up to do right now. For now,
531 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000532 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000533 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000534 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Chris Lattnerf4021e72007-08-23 05:46:52 +0000536 } else {
537 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattnerf4021e72007-08-23 05:46:52 +0000539 // We already verified that the expression has a i-c-e value (C99
540 // 6.8.4.2p3) - get that value now.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000541 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000542
543 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
544 HasDependentValue = true;
545 break;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Anders Carlsson51fe9962008-11-22 21:04:56 +0000548 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattnerf4021e72007-08-23 05:46:52 +0000550 // Convert the value to the same width/sign as the condition.
551 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000552 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000553 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000554
Chris Lattner1e0a3902008-01-16 19:17:22 +0000555 // If the LHS is not the same type as the condition, insert an implicit
556 // cast.
John McCall2de56d12010-08-25 11:45:40 +0000557 ImpCastExprToType(Lo, CondType, CK_IntegralCast);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000558 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000560 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000561 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000563 CS->getRHS()->isValueDependent()) {
564 HasDependentValue = true;
565 break;
566 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000567 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000568 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000569 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000570 }
571 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000572
573 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000574 // If we don't have a default statement, check whether the
575 // condition is constant.
576 llvm::APSInt ConstantCondValue;
577 bool HasConstantCond = false;
578 bool ShouldCheckConstantCond = false;
579 if (!HasDependentValue && !TheDefaultStmt) {
580 Expr::EvalResult Result;
581 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
582 if (HasConstantCond) {
583 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
584 ConstantCondValue = Result.Val.getInt();
585 ShouldCheckConstantCond = true;
586
587 assert(ConstantCondValue.getBitWidth() == CondWidth &&
588 ConstantCondValue.isSigned() == CondIsSigned);
589 }
590 }
591
Douglas Gregordbb26db2009-05-15 23:57:33 +0000592 // Sort all the scalar case values so we can easily detect duplicates.
593 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
594
595 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000596 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
597 if (ShouldCheckConstantCond &&
598 CaseVals[i].first == ConstantCondValue)
599 ShouldCheckConstantCond = false;
600
601 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000602 // If we have a duplicate, report it.
Mike Stump1eb44332009-09-09 15:08:12 +0000603 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCall0fb97082010-05-18 03:19:21 +0000604 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
605 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000606 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000607 // FIXME: We really want to remove the bogus case stmt from the
608 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000609 CaseListIsErroneous = true;
610 }
611 }
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregordbb26db2009-05-15 23:57:33 +0000614 // Detect duplicate case ranges, which usually don't exist at all in
615 // the first place.
616 if (!CaseRanges.empty()) {
617 // Sort all the case ranges by their low value so we can easily detect
618 // overlaps between ranges.
619 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Douglas Gregordbb26db2009-05-15 23:57:33 +0000621 // Scan the ranges, computing the high values and removing empty ranges.
622 std::vector<llvm::APSInt> HiVals;
623 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000624 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000625 CaseStmt *CR = CaseRanges[i].second;
626 Expr *Hi = CR->getRHS();
627 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Douglas Gregordbb26db2009-05-15 23:57:33 +0000629 // Convert the value to the same width/sign as the condition.
630 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000631 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000632 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Douglas Gregordbb26db2009-05-15 23:57:33 +0000634 // If the LHS is not the same type as the condition, insert an implicit
635 // cast.
John McCall2de56d12010-08-25 11:45:40 +0000636 ImpCastExprToType(Hi, CondType, CK_IntegralCast);
Douglas Gregordbb26db2009-05-15 23:57:33 +0000637 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Douglas Gregordbb26db2009-05-15 23:57:33 +0000639 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000640 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000641 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
642 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000643 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000644 CaseRanges.erase(CaseRanges.begin()+i);
645 --i, --e;
646 continue;
647 }
John McCall0fb97082010-05-18 03:19:21 +0000648
649 if (ShouldCheckConstantCond &&
650 LoVal <= ConstantCondValue &&
651 ConstantCondValue <= HiVal)
652 ShouldCheckConstantCond = false;
653
Douglas Gregordbb26db2009-05-15 23:57:33 +0000654 HiVals.push_back(HiVal);
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Douglas Gregordbb26db2009-05-15 23:57:33 +0000657 // Rescan the ranges, looking for overlap with singleton values and other
658 // ranges. Since the range list is sorted, we only need to compare case
659 // ranges with their neighbors.
660 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
661 llvm::APSInt &CRLo = CaseRanges[i].first;
662 llvm::APSInt &CRHi = HiVals[i];
663 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Douglas Gregordbb26db2009-05-15 23:57:33 +0000665 // Check to see whether the case range overlaps with any
666 // singleton cases.
667 CaseStmt *OverlapStmt = 0;
668 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Douglas Gregordbb26db2009-05-15 23:57:33 +0000670 // Find the smallest value >= the lower bound. If I is in the
671 // case range, then we have overlap.
672 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
673 CaseVals.end(), CRLo,
674 CaseCompareFunctor());
675 if (I != CaseVals.end() && I->first < CRHi) {
676 OverlapVal = I->first; // Found overlap with scalar.
677 OverlapStmt = I->second;
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Douglas Gregordbb26db2009-05-15 23:57:33 +0000680 // Find the smallest value bigger than the upper bound.
681 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
682 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
683 OverlapVal = (I-1)->first; // Found overlap with scalar.
684 OverlapStmt = (I-1)->second;
685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Douglas Gregordbb26db2009-05-15 23:57:33 +0000687 // Check to see if this case stmt overlaps with the subsequent
688 // case range.
689 if (i && CRLo <= HiVals[i-1]) {
690 OverlapVal = HiVals[i-1]; // Found overlap with range.
691 OverlapStmt = CaseRanges[i-1].second;
692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Douglas Gregordbb26db2009-05-15 23:57:33 +0000694 if (OverlapStmt) {
695 // If we have a duplicate, report it.
696 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
697 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000698 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000699 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000700 // FIXME: We really want to remove the bogus case stmt from the
701 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000702 CaseListIsErroneous = true;
703 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000704 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000705 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000706
John McCall0fb97082010-05-18 03:19:21 +0000707 // Complain if we have a constant condition and we didn't find a match.
708 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
709 // TODO: it would be nice if we printed enums as enums, chars as
710 // chars, etc.
711 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
712 << ConstantCondValue.toString(10)
713 << CondExpr->getSourceRange();
714 }
715
716 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000717 // values. We only issue a warning if there is not 'default:', but
718 // we still do the analysis to preserve this information in the AST
719 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000720 //
Chris Lattnerce784612010-09-16 17:09:42 +0000721 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000722
Douglas Gregorba915af2010-02-08 22:24:16 +0000723 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000724 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000725 const EnumDecl *ED = ET->getDecl();
726 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
727 EnumValsTy EnumVals;
728
John McCall0fb97082010-05-18 03:19:21 +0000729 // Gather all enum values, set their type and sort them,
730 // allowing easier comparison with CaseVals.
731 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000732 EDI != ED->enumerator_end(); ++EDI) {
733 llvm::APSInt Val = EDI->getInitVal();
734 AdjustAPSInt(Val, CondWidth, CondIsSigned);
735 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000736 }
737 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000738 EnumValsTy::iterator EIend =
739 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000740
741 // See which case values aren't in enum.
742 // TODO: we might want to check whether case values are out of the
743 // enum even if we don't want to check whether all cases are handled.
744 if (!TheDefaultStmt) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000745 EnumValsTy::const_iterator EI = EnumVals.begin();
746 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCall0fb97082010-05-18 03:19:21 +0000747 CI != CaseVals.end(); CI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000748 while (EI != EIend && EI->first < CI->first)
749 EI++;
750 if (EI == EIend || EI->first > CI->first)
John McCall0fb97082010-05-18 03:19:21 +0000751 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
752 << ED->getDeclName();
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000753 }
754 // See which of case ranges aren't in enum
755 EI = EnumVals.begin();
756 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCall0fb97082010-05-18 03:19:21 +0000757 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000758 while (EI != EIend && EI->first < RI->first)
759 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000760
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000761 if (EI == EIend || EI->first != RI->first) {
762 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
763 << ED->getDeclName();
764 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000765
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000766 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +0000767 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000768 while (EI != EIend && EI->first < Hi)
769 EI++;
770 if (EI == EIend || EI->first != Hi)
771 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
772 << ED->getDeclName();
773 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000774 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000775
Ted Kremenek559fb552010-09-09 00:05:53 +0000776 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000777 CaseValsTy::const_iterator CI = CaseVals.begin();
778 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000779 bool hasCasesNotInSwitch = false;
780
Chris Lattnerce784612010-09-16 17:09:42 +0000781 llvm::SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000782
Ted Kremenek559fb552010-09-09 00:05:53 +0000783 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000784 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000785 llvm::APSInt CIVal;
786 while (CI != CaseVals.end() && CI->first < EI->first)
787 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000788
Douglas Gregorba915af2010-02-08 22:24:16 +0000789 if (CI != CaseVals.end() && CI->first == EI->first)
790 continue;
791
Ted Kremenek559fb552010-09-09 00:05:53 +0000792 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +0000793 for (; RI != CaseRanges.end(); RI++) {
794 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +0000795 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +0000796 if (EI->first <= Hi)
797 break;
798 }
799
Ted Kremenek559fb552010-09-09 00:05:53 +0000800 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000801 hasCasesNotInSwitch = true;
802 if (!TheDefaultStmt)
Chris Lattnerce784612010-09-16 17:09:42 +0000803 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000804 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000805 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000806
Chris Lattnerce784612010-09-16 17:09:42 +0000807 // Produce a nice diagnostic if multiple values aren't handled.
808 switch (UnhandledNames.size()) {
809 case 0: break;
810 case 1:
811 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
812 << UnhandledNames[0];
813 break;
814 case 2:
815 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
816 << UnhandledNames[0] << UnhandledNames[1];
817 break;
818 case 3:
819 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
820 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
821 break;
822 default:
823 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
824 << (unsigned)UnhandledNames.size()
825 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
826 break;
827 }
Ted Kremenek559fb552010-09-09 00:05:53 +0000828
829 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000830 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +0000831 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000832 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000833
Mike Stump390b4cc2009-05-16 07:39:55 +0000834 // FIXME: If the case list was broken is some way, we don't have a good system
835 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000836 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +0000837 return StmtError();
838
Sebastian Redlde307472009-01-11 00:38:46 +0000839 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000840}
841
John McCall60d7b3a2010-08-24 06:29:42 +0000842StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000843Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +0000844 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +0000845 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000846
Douglas Gregor5656e142009-11-24 21:15:44 +0000847 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000848 if (CondVar) {
849 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000850 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000851 if (CondResult.isInvalid())
852 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +0000853 }
John McCall9ae2f072010-08-23 23:25:46 +0000854 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000855 if (!ConditionExpr)
856 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000857
John McCall9ae2f072010-08-23 23:25:46 +0000858 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000860 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +0000861 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000862}
863
John McCall60d7b3a2010-08-24 06:29:42 +0000864StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000865Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +0000866 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +0000867 Expr *Cond, SourceLocation CondRParen) {
868 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +0000869
John McCall9ae2f072010-08-23 23:25:46 +0000870 if (CheckBooleanCondition(Cond, DoLoc))
John McCall5a881bb2009-10-12 21:59:07 +0000871 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000872
John McCallb4eb64d2010-10-08 02:01:28 +0000873 CheckImplicitConversions(Cond, DoLoc);
John McCall4765fa02010-12-06 08:20:24 +0000874 ExprResult CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000875 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000876 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000877 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000878
John McCall9ae2f072010-08-23 23:25:46 +0000879 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +0000880
John McCall9ae2f072010-08-23 23:25:46 +0000881 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +0000882}
883
John McCall60d7b3a2010-08-24 06:29:42 +0000884StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +0000885Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000886 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000887 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +0000888 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000889 if (!getLangOptions().CPlusPlus) {
890 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000891 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
892 // declare identifiers for objects having storage class 'auto' or
893 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000894 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
895 DI!=DE; ++DI) {
896 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +0000897 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000898 VD = 0;
899 if (VD == 0)
900 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
901 // FIXME: mark decl erroneous!
902 }
Chris Lattnerae3b7012007-08-28 05:03:08 +0000903 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000905
John McCall60d7b3a2010-08-24 06:29:42 +0000906 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000907 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000908 if (secondVar) {
909 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000910 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000911 if (SecondResult.isInvalid())
912 return StmtError();
913 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000914
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000915 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916
Anders Carlsson3af708f2009-08-01 01:39:59 +0000917 DiagnoseUnusedExprResult(First);
918 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +0000919 DiagnoseUnusedExprResult(Body);
920
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000921 return Owned(new (Context) ForStmt(Context, First,
922 SecondResult.take(), ConditionVar,
923 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000924 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000925}
926
John McCallf6a16482010-12-04 03:47:34 +0000927/// In an Objective C collection iteration statement:
928/// for (x in y)
929/// x can be an arbitrary l-value expression. Bind it up as a
930/// full-expression.
931StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
932 CheckImplicitConversions(E);
John McCall4765fa02010-12-06 08:20:24 +0000933 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCallf6a16482010-12-04 03:47:34 +0000934 if (Result.isInvalid()) return StmtError();
935 return Owned(static_cast<Stmt*>(Result.get()));
936}
937
John McCall60d7b3a2010-08-24 06:29:42 +0000938StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +0000939Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
940 SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000941 Stmt *First, Expr *Second,
942 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian20552d22008-01-10 20:33:58 +0000943 if (First) {
944 QualType FirstType;
945 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +0000946 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000947 return StmtError(Diag((*DS->decl_begin())->getLocation(),
948 diag::err_toomany_element_decls));
949
Chris Lattner7e24e822009-03-28 06:33:19 +0000950 Decl *D = DS->getSingleDecl();
Ted Kremenekf34afee2008-10-06 20:58:11 +0000951 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000952 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
953 // declare identifiers for objects having storage class 'auto' or
954 // 'register'.
Steve Naroff248a7532008-04-15 22:42:06 +0000955 VarDecl *VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000956 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000957 return StmtError(Diag(VD->getLocation(),
958 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000959 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +0000960 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +0000961 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000962 return StmtError(Diag(First->getLocStart(),
963 diag::err_selector_element_not_lvalue)
964 << First->getSourceRange());
965
Mike Stump1eb44332009-09-09 15:08:12 +0000966 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000967 }
Douglas Gregorc3203e72010-04-22 23:10:45 +0000968 if (!FirstType->isDependentType() &&
969 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +0000970 !FirstType->isBlockPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000971 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000972 << FirstType << First->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000973 }
Douglas Gregorc3203e72010-04-22 23:10:45 +0000974 if (Second && !Second->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +0000975 DefaultFunctionArrayLvalueConversion(Second);
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000976 QualType SecondType = Second->getType();
Steve Narofff4954562009-07-16 15:41:00 +0000977 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000978 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000979 << SecondType << Second->getSourceRange();
Fariborz Jahanianea161102010-08-12 22:25:42 +0000980 else if (const ObjCObjectPointerType *OPT =
981 SecondType->getAsObjCInterfacePointerType()) {
982 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983 IdentifierInfo* selIdent =
Fariborz Jahanianea161102010-08-12 22:25:42 +0000984 &Context.Idents.get("countByEnumeratingWithState");
985 KeyIdents.push_back(selIdent);
986 selIdent = &Context.Idents.get("objects");
987 KeyIdents.push_back(selIdent);
988 selIdent = &Context.Idents.get("count");
989 KeyIdents.push_back(selIdent);
990 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
991 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000992 if (!IDecl->isForwardDecl() &&
Fariborz Jahanianea161102010-08-12 22:25:42 +0000993 !IDecl->lookupInstanceMethod(CSelector)) {
Fariborz Jahanian80a785c2010-08-12 22:33:42 +0000994 // Must further look into private implementation methods.
Fariborz Jahanianea161102010-08-12 22:25:42 +0000995 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
996 Diag(ForLoc, diag::warn_collection_expr_type)
997 << SecondType << CSelector << Second->getSourceRange();
998 }
999 }
1000 }
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001001 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001002 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1003 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001004}
Reid Spencer5f016e22007-07-11 17:01:13 +00001005
Chris Lattner57ad3782011-02-17 20:34:02 +00001006StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1007 SourceLocation LabelLoc,
1008 LabelDecl *TheDecl) {
1009 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001010 TheDecl->setUsed();
1011 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001012}
1013
John McCall60d7b3a2010-08-24 06:29:42 +00001014StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00001015Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001016 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00001017 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001018 if (!E->isTypeDependent()) {
1019 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00001020 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001021 AssignConvertType ConvTy =
Chandler Carruth28779982010-01-31 10:26:25 +00001022 CheckSingleAssignmentConstraints(DestTy, E);
1023 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001024 return StmtError();
1025 }
John McCallb60a77e2010-08-01 00:26:45 +00001026
John McCall781472f2010-08-25 08:40:02 +00001027 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00001028
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001029 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001030}
1031
John McCall60d7b3a2010-08-24 06:29:42 +00001032StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001033Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 Scope *S = CurScope->getContinueParent();
1035 if (!S) {
1036 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001037 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001039
Ted Kremenek8189cde2009-02-07 01:47:29 +00001040 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001041}
1042
John McCall60d7b3a2010-08-24 06:29:42 +00001043StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001044Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 Scope *S = CurScope->getBreakParent();
1046 if (!S) {
1047 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001048 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001050
Ted Kremenek8189cde2009-02-07 01:47:29 +00001051 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001052}
1053
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001054/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001055/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00001056///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001057/// \param ReturnType If we're determining the copy elision candidate for
1058/// a return statement, this is the return type of the function. If we're
1059/// determining the copy elision candidate for a throw expression, this will
1060/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00001061///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001062/// \param E The expression being returned from the function or block, or
1063/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00001064///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001065/// \param AllowFunctionParameter
Douglas Gregor5077c382010-05-15 06:01:05 +00001066///
1067/// \returns The NRVO candidate variable, if the return statement may use the
1068/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001069const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1070 Expr *E,
1071 bool AllowFunctionParameter) {
1072 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001073 // - in a return statement in a function with ...
1074 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001075 if (!ReturnType.isNull()) {
1076 if (!ReturnType->isRecordType())
1077 return 0;
1078 // ... the same cv-unqualified type as the function return type ...
1079 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1080 return 0;
1081 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001082
1083 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001084 // (other than a function or catch-clause parameter)) ...
1085 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001086 if (!DR)
Douglas Gregor5077c382010-05-15 06:01:05 +00001087 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001088 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1089 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00001090 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001092 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregord86c4772010-05-15 06:46:45 +00001093 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001094 !VD->getType().isVolatileQualified() &&
Douglas Gregor4a46c772011-01-21 18:20:49 +00001095 ((VD->getKind() == Decl::Var) ||
1096 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor5077c382010-05-15 06:01:05 +00001097 return VD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001098
Douglas Gregor5077c382010-05-15 06:01:05 +00001099 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001100}
1101
Douglas Gregor07f402c2011-01-21 21:08:57 +00001102/// \brief Perform the initialization of a potentially-movable value, which
1103/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00001104///
1105/// This routine implements C++0x [class.copy]p33, which attempts to treat
1106/// returned lvalues as rvalues in certain cases (to prefer move construction),
1107/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00001109Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1110 const VarDecl *NRVOCandidate,
1111 QualType ResultType,
1112 Expr *Value) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00001113 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001114 // When the criteria for elision of a copy operation are met or would
1115 // be met save for the fact that the source object is a function
1116 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00001117 // overload resolution to select the constructor for the copy is first
1118 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00001119 ExprResult Res = ExprError();
Douglas Gregor07f402c2011-01-21 21:08:57 +00001120 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001121 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001122 Value->getType(), CK_LValueToRValue,
1123 Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001124
Douglas Gregorcc15f012011-01-21 19:38:21 +00001125 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00001127 = InitializationKind::CreateCopy(Value->getLocStart(),
1128 Value->getLocStart());
1129 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001130
1131 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00001132 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001133 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00001134 // is performed again, considering the object as an lvalue.
1135 if (Seq.getKind() != InitializationSequence::FailedSequence) {
1136 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1137 StepEnd = Seq.step_end();
1138 Step != StepEnd; ++Step) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001139 if (Step->Kind
Douglas Gregorcc15f012011-01-21 19:38:21 +00001140 != InitializationSequence::SK_ConstructorInitialization)
1141 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001142
1143 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00001144 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001145
Douglas Gregorcc15f012011-01-21 19:38:21 +00001146 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00001147 = Constructor->getParamDecl(0)->getType()
1148 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001149
Douglas Gregorcc15f012011-01-21 19:38:21 +00001150 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00001152 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1153 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00001154 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001155
Douglas Gregorcc15f012011-01-21 19:38:21 +00001156 // Promote "AsRvalue" to the heap, since we now need this
1157 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00001158 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001159 CK_LValueToRValue, Value, 0,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001160 VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001161
Douglas Gregorcc15f012011-01-21 19:38:21 +00001162 // Complete type-checking the initialization of the return type
1163 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00001164 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00001165 }
1166 }
1167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001168
Douglas Gregorcc15f012011-01-21 19:38:21 +00001169 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001170 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00001171 // (again) now with the return value expression as written.
1172 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00001173 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001174
Douglas Gregorcc15f012011-01-21 19:38:21 +00001175 return Res;
1176}
1177
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001178/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001179///
John McCall60d7b3a2010-08-24 06:29:42 +00001180StmtResult
Steve Naroff4eb206b2008-09-03 18:15:37 +00001181Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00001182 // If this is the first return we've seen in the block, infer the type of
1183 // the block from it.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001184 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001185 if (CurBlock->ReturnType.isNull()) {
Steve Naroffc50a4a52008-09-16 22:25:10 +00001186 if (RetValExp) {
Steve Naroff16564422008-09-24 22:26:48 +00001187 // Don't call UsualUnaryConversions(), since we don't want to do
1188 // integer promotions here.
Douglas Gregora873dfc2010-02-03 00:27:59 +00001189 DefaultFunctionArrayLvalueConversion(RetValExp);
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001190 CurBlock->ReturnType = RetValExp->getType();
1191 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1192 // We have to remove a 'const' added to copied-in variable which was
1193 // part of the implementation spec. and not the actual qualifier for
1194 // the variable.
1195 if (CDRE->isConstQualAdded())
John McCall49f4e1c2010-12-10 11:01:00 +00001196 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001197 }
Steve Naroffc50a4a52008-09-16 22:25:10 +00001198 } else
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001199 CurBlock->ReturnType = Context.VoidTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00001200 }
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001201 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001202
John McCall711c52b2011-01-05 12:14:39 +00001203 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump6c92fa72009-04-29 21:40:37 +00001204 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1205 << getCurFunctionOrMethodDecl()->getDeclName();
1206 return StmtError();
1207 }
1208
Steve Naroff4eb206b2008-09-03 18:15:37 +00001209 // Otherwise, verify that this result type matches the previous one. We are
1210 // pickier with blocks than for normal functions because we don't have GCC
1211 // compatibility to worry about here.
Douglas Gregor5077c382010-05-15 06:01:05 +00001212 ReturnStmt *Result = 0;
Steve Naroff4eb206b2008-09-03 18:15:37 +00001213 if (CurBlock->ReturnType->isVoidType()) {
1214 if (RetValExp) {
1215 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001216 RetValExp = 0;
1217 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001218 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1219 } else if (!RetValExp) {
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001220 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
Douglas Gregor5077c382010-05-15 06:01:05 +00001221 } else {
1222 const VarDecl *NRVOCandidate = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001223
Douglas Gregor5077c382010-05-15 06:01:05 +00001224 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1225 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001226
Douglas Gregor5077c382010-05-15 06:01:05 +00001227 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1228 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1229 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001230
Douglas Gregor5077c382010-05-15 06:01:05 +00001231 // In C++ the return statement is handled via a copy initialization.
1232 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001233 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001234 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001235 FnRetType,
1236 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001237 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001238 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00001239 if (Res.isInvalid()) {
1240 // FIXME: Cleanup temporaries here, anyway?
1241 return StmtError();
1242 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001243
John McCallb4eb64d2010-10-08 02:01:28 +00001244 if (RetValExp) {
1245 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00001246 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00001247 }
Mike Stump98eb8a72009-02-04 22:31:32 +00001248
Douglas Gregor5077c382010-05-15 06:01:05 +00001249 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00001251 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Anders Carlssonc6acbc52010-01-29 18:30:20 +00001252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001253
Douglas Gregor5077c382010-05-15 06:01:05 +00001254 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001255 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001256
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00001258 // return statement in our scope for later processing.
1259 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1260 !CurContext->isDependentContext())
1261 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001262
Douglas Gregor5077c382010-05-15 06:01:05 +00001263 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001264}
Reid Spencer5f016e22007-07-11 17:01:13 +00001265
John McCall60d7b3a2010-08-24 06:29:42 +00001266StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001267Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001268 if (getCurBlock())
Steve Naroff4eb206b2008-09-03 18:15:37 +00001269 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001270
Chris Lattner371f2582008-12-04 23:50:19 +00001271 QualType FnRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00001272 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00001273 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00001274 if (FD->hasAttr<NoReturnAttr>() ||
1275 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00001276 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpf7c41da2009-04-29 00:43:21 +00001277 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpf7c41da2009-04-29 00:43:21 +00001278 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Naroffc97fb9a2009-03-03 00:45:38 +00001279 FnRetType = MD->getResultType();
1280 else // If we don't have a function/method context, bail.
1281 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Douglas Gregor5077c382010-05-15 06:01:05 +00001283 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00001284 if (FnRetType->isVoidType()) {
Douglas Gregor1be8aee2009-10-01 23:25:31 +00001285 if (RetValExp && !RetValExp->isTypeDependent()) {
1286 // C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner65ce04b2008-12-18 02:01:17 +00001287 unsigned D = diag::ext_return_has_expr;
1288 if (RetValExp->getType()->isVoidType())
1289 D = diag::ext_return_has_void_expr;
John McCallf6a16482010-12-04 03:47:34 +00001290 else {
1291 IgnoredValueConversions(RetValExp);
1292 ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid);
1293 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001294
Chris Lattnere878eb02008-12-18 02:03:48 +00001295 // return (some void expression); is legal in C++.
1296 if (D != diag::ext_return_has_void_expr ||
1297 !getLangOptions().CPlusPlus) {
1298 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1299 Diag(ReturnLoc, D)
1300 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1301 << RetValExp->getSourceRange();
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCallb4eb64d2010-10-08 02:01:28 +00001304 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00001305 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001307
Douglas Gregor5077c382010-05-15 06:01:05 +00001308 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1309 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001310 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1311 // C99 6.8.6.4p1 (ext_ since GCC warns)
1312 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1313
1314 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00001315 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00001316 else
Chris Lattner08631c52008-11-23 21:45:46 +00001317 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00001318 Result = new (Context) ReturnStmt(ReturnLoc);
1319 } else {
1320 const VarDecl *NRVOCandidate = 0;
1321 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1322 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001323
Douglas Gregor5077c382010-05-15 06:01:05 +00001324 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1325 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1326 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001327
Douglas Gregor5077c382010-05-15 06:01:05 +00001328 // In C++ the return statement is handled via a copy initialization.
1329 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001330 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001331 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001332 FnRetType,
1333 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001334 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001335 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00001336 if (Res.isInvalid()) {
1337 // FIXME: Cleanup temporaries here, anyway?
1338 return StmtError();
1339 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001340
Douglas Gregor5077c382010-05-15 06:01:05 +00001341 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001342 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00001343 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001345
John McCallb4eb64d2010-10-08 02:01:28 +00001346 if (RetValExp) {
1347 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00001348 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00001349 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001350 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00001351 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001352
1353 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00001354 // return statement in our scope for later processing.
1355 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1356 !CurContext->isDependentContext())
1357 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Douglas Gregor5077c382010-05-15 06:01:05 +00001359 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001360}
1361
Chris Lattner810f6d52009-03-13 17:38:01 +00001362/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1363/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1364/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1365/// provide a strong guidance to not use it.
1366///
1367/// This method checks to see if the argument is an acceptable l-value and
1368/// returns false if it is a case we can handle.
1369static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00001370 // Type dependent expressions will be checked during instantiation.
1371 if (E->isTypeDependent())
1372 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001373
John McCall7eb0a9e2010-11-24 05:12:34 +00001374 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00001375 return false; // Cool, this is an lvalue.
1376
1377 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1378 // are supposed to allow.
1379 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00001380 if (E != E2 && E2->isLValue()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00001381 if (!S.getLangOptions().HeinousExtensions)
1382 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1383 << E->getSourceRange();
1384 else
1385 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1386 << E->getSourceRange();
1387 // Accept, even if we emitted an error diagnostic.
1388 return false;
1389 }
1390
1391 // None of the above, just randomly invalid non-lvalue.
1392 return true;
1393}
1394
1395
John McCall60d7b3a2010-08-24 06:29:42 +00001396StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001397 bool IsSimple,
1398 bool IsVolatile,
1399 unsigned NumOutputs,
1400 unsigned NumInputs,
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001401 IdentifierInfo **Names,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001402 MultiExprArg constraints,
1403 MultiExprArg exprs,
John McCall9ae2f072010-08-23 23:25:46 +00001404 Expr *asmString,
Sebastian Redl3037ed02009-01-18 16:53:17 +00001405 MultiExprArg clobbers,
Mike Stump3b11fd32010-01-04 22:37:17 +00001406 SourceLocation RParenLoc,
1407 bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00001408 unsigned NumClobbers = clobbers.size();
1409 StringLiteral **Constraints =
1410 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00001411 Expr **Exprs = exprs.get();
1412 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00001413 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1414
Anders Carlsson03eb5432009-01-27 20:38:24 +00001415 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner1708b962008-08-18 19:55:17 +00001417 // The parser verifies that there is a string literal here.
Chris Lattner6bc52112008-07-23 06:46:56 +00001418 if (AsmString->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001419 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1420 << AsmString->getSourceRange());
1421
Chris Lattner1708b962008-08-18 19:55:17 +00001422 for (unsigned i = 0; i != NumOutputs; i++) {
1423 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001424 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001425 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1426 << Literal->getSourceRange());
1427
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001428 llvm::StringRef OutputName;
1429 if (Names[i])
1430 OutputName = Names[i]->getName();
1431
1432 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Chris Lattner432c8692009-04-26 17:19:08 +00001433 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001434 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001435 diag::err_asm_invalid_output_constraint)
1436 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00001437
Anders Carlssond04c6e22007-11-27 04:11:28 +00001438 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00001439 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00001440 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00001441 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001442 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00001443 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattner44def072009-04-26 07:16:29 +00001446 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001447 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001448
Chris Lattner806503f2009-05-03 05:55:43 +00001449 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1450
Anders Carlsson04728b72007-11-23 19:43:50 +00001451 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00001452 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001453 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001454 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1455 << Literal->getSourceRange());
1456
Anders Carlssonff93dbd2010-01-30 22:25:16 +00001457 llvm::StringRef InputName;
1458 if (Names[i])
1459 InputName = Names[i]->getName();
1460
1461 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Jay Foadbeaaccd2009-05-21 09:52:38 +00001462 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001463 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00001464 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001465 diag::err_asm_invalid_input_constraint)
1466 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00001467 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001468
Eli Friedman72056a22009-05-03 07:49:42 +00001469 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00001470
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001471 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00001472 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00001473 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00001474 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001475 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00001476 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001477 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001478 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001479
Chris Lattner44def072009-04-26 07:16:29 +00001480 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001481 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00001482 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001483 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00001484 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001485 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001486 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Douglas Gregora873dfc2010-02-03 00:27:59 +00001489 DefaultFunctionArrayLvalueConversion(Exprs[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Chris Lattner806503f2009-05-03 05:55:43 +00001491 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001492 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001493
Anders Carlsson6fa90862007-11-25 00:25:21 +00001494 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00001495 for (unsigned i = 0; i != NumClobbers; i++) {
1496 StringLiteral *Literal = Clobbers[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001497 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001498 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1499 << Literal->getSourceRange());
1500
Anders Carlssonfdba9c02010-01-30 19:34:25 +00001501 llvm::StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00001502
Anders Carlssonfdba9c02010-01-30 19:34:25 +00001503 if (!Context.Target.isValidGCCRegisterName(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001504 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00001505 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00001506 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001507
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001508 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001509 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1510 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00001511 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001512 // Validate the asm string, ensuring it makes sense given the operands we
1513 // have.
1514 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1515 unsigned DiagOffs;
1516 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00001517 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1518 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001519 return StmtError();
1520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Chris Lattner806503f2009-05-03 05:55:43 +00001522 // Validate tied input operands for type mismatches.
1523 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1524 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Chris Lattner806503f2009-05-03 05:55:43 +00001526 // If this is a tied constraint, verify that the output and input have
1527 // either exactly the same type, or that they are int/ptr operands with the
1528 // same size (int/long, int*/long, are ok etc).
1529 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner806503f2009-05-03 05:55:43 +00001531 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001532 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001533 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner7adaa182009-05-03 05:59:17 +00001534 QualType InTy = InputExpr->getType();
1535 QualType OutTy = OutputExpr->getType();
1536 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00001537 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Chris Lattneraab64d02010-04-23 17:27:29 +00001539 // Decide if the input and output are in the same domain (integer/ptr or
1540 // floating point.
1541 enum AsmDomain {
1542 AD_Int, AD_FP, AD_Other
1543 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001544
Chris Lattneraab64d02010-04-23 17:27:29 +00001545 if (InTy->isIntegerType() || InTy->isPointerType())
1546 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001547 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00001548 InputDomain = AD_FP;
1549 else
1550 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Chris Lattneraab64d02010-04-23 17:27:29 +00001552 if (OutTy->isIntegerType() || OutTy->isPointerType())
1553 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001554 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00001555 OutputDomain = AD_FP;
1556 else
1557 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001558
Chris Lattneraab64d02010-04-23 17:27:29 +00001559 // They are ok if they are the same size and in the same domain. This
1560 // allows tying things like:
1561 // void* to int*
1562 // void* to int if they are the same size.
1563 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001564 //
Chris Lattneraab64d02010-04-23 17:27:29 +00001565 uint64_t OutSize = Context.getTypeSize(OutTy);
1566 uint64_t InSize = Context.getTypeSize(InTy);
1567 if (OutSize == InSize && InputDomain == OutputDomain &&
1568 InputDomain != AD_Other)
1569 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001570
Chris Lattneraab64d02010-04-23 17:27:29 +00001571 // If the smaller input/output operand is not mentioned in the asm string,
1572 // then we can promote it and the asm string won't notice. Check this
1573 // case now.
1574 bool SmallerValueMentioned = false;
1575 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1576 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1577 if (!Piece.isOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Chris Lattneraab64d02010-04-23 17:27:29 +00001579 // If this is a reference to the input and if the input was the smaller
1580 // one, then we have to reject this asm.
1581 if (Piece.getOperandNo() == i+NumOutputs) {
1582 if (InSize < OutSize) {
1583 SmallerValueMentioned = true;
1584 break;
Chris Lattner3351f112009-05-03 08:32:32 +00001585 }
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Chris Lattneraab64d02010-04-23 17:27:29 +00001588 // If this is a reference to the input and if the input was the smaller
1589 // one, then we have to reject this asm.
1590 if (Piece.getOperandNo() == TiedTo) {
1591 if (InSize > OutSize) {
1592 SmallerValueMentioned = true;
1593 break;
1594 }
1595 }
Chris Lattner806503f2009-05-03 05:55:43 +00001596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattneraab64d02010-04-23 17:27:29 +00001598 // If the smaller value wasn't mentioned in the asm string, and if the
1599 // output was a register, just extend the shorter one to the size of the
1600 // larger one.
1601 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1602 OutputConstraintInfos[TiedTo].allowsRegister())
1603 continue;
1604
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001605 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00001606 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00001607 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00001608 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00001609 return StmtError();
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001612 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00001613}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001614
John McCall60d7b3a2010-08-24 06:29:42 +00001615StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00001616Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00001617 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00001618 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00001619 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00001620 if (Var && Var->isInvalidDecl())
1621 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001622
John McCall9ae2f072010-08-23 23:25:46 +00001623 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001624}
1625
John McCall60d7b3a2010-08-24 06:29:42 +00001626StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001627Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1628 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00001629}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001630
John McCall60d7b3a2010-08-24 06:29:42 +00001631StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001632Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00001633 MultiStmtArg CatchStmts, Stmt *Finally) {
John McCall781472f2010-08-25 08:40:02 +00001634 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001635 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00001636 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1637 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001638 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00001639 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001640}
1641
John McCall60d7b3a2010-08-24 06:29:42 +00001642StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001643 Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00001644 if (Throw) {
John McCall5e3c67b2010-12-15 04:42:30 +00001645 DefaultLvalueConversion(Throw);
1646
Douglas Gregord1377b22010-04-22 21:44:01 +00001647 QualType ThrowType = Throw->getType();
1648 // Make sure the expression type is an ObjC pointer or "void *".
1649 if (!ThrowType->isDependentType() &&
1650 !ThrowType->isObjCObjectPointerType()) {
1651 const PointerType *PT = ThrowType->getAs<PointerType>();
1652 if (!PT || !PT->getPointeeType()->isVoidType())
1653 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1654 << Throw->getType() << Throw->getSourceRange());
1655 }
1656 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657
John McCall9ae2f072010-08-23 23:25:46 +00001658 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00001659}
1660
John McCall60d7b3a2010-08-24 06:29:42 +00001661StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001662Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00001663 Scope *CurScope) {
John McCall9ae2f072010-08-23 23:25:46 +00001664 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00001665 // @throw without an expression designates a rethrow (which much occur
1666 // in the context of an @catch clause).
1667 Scope *AtCatchParent = CurScope;
1668 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1669 AtCatchParent = AtCatchParent->getParent();
1670 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00001671 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001672 }
1673
John McCall9ae2f072010-08-23 23:25:46 +00001674 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00001675}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001676
John McCall60d7b3a2010-08-24 06:29:42 +00001677StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001678Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1679 Stmt *SyncBody) {
John McCall781472f2010-08-25 08:40:02 +00001680 getCurFunction()->setHasBranchProtectedScope();
Chris Lattner46c3c4b2009-04-21 06:01:00 +00001681
John McCall5e3c67b2010-12-15 04:42:30 +00001682 DefaultLvalueConversion(SyncExpr);
1683
Chris Lattnera868a202009-04-21 06:11:25 +00001684 // Make sure the expression type is an ObjC pointer or "void *".
Douglas Gregor8fdc13a2010-04-22 22:01:21 +00001685 if (!SyncExpr->getType()->isDependentType() &&
1686 !SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattnera868a202009-04-21 06:11:25 +00001688 if (!PT || !PT->getPointeeType()->isVoidType())
1689 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1690 << SyncExpr->getType() << SyncExpr->getSourceRange());
1691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
John McCall9ae2f072010-08-23 23:25:46 +00001693 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00001694}
Sebastian Redl4b07b292008-12-22 19:15:10 +00001695
1696/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1697/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00001698StmtResult
John McCalld226f652010-08-21 09:40:31 +00001699Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00001700 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00001701 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001702 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00001703 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00001704 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00001705}
Sebastian Redl8351da02008-12-22 21:35:02 +00001706
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001707namespace {
1708
Sebastian Redlc447aba2009-07-29 17:15:45 +00001709class TypeWithHandler {
1710 QualType t;
1711 CXXCatchStmt *stmt;
1712public:
1713 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1714 : t(type), stmt(statement) {}
1715
John McCall0953e762009-09-24 19:53:00 +00001716 // An arbitrary order is fine as long as it places identical
1717 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00001718 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00001719 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00001720 return true;
John McCall0953e762009-09-24 19:53:00 +00001721 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00001722 return false;
1723 else
1724 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Sebastian Redlc447aba2009-07-29 17:15:45 +00001727 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00001728 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00001729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Sebastian Redlc447aba2009-07-29 17:15:45 +00001731 CXXCatchStmt *getCatchStmt() const { return stmt; }
1732 SourceLocation getTypeSpecStartLoc() const {
1733 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1734 }
1735};
1736
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001737}
1738
Sebastian Redl8351da02008-12-22 21:35:02 +00001739/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1740/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00001741StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001742Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00001743 MultiStmtArg RawHandlers) {
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00001744 if (!getLangOptions().Exceptions)
Anders Carlssonb1fba312011-02-19 21:53:09 +00001745 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00001746
Sebastian Redl8351da02008-12-22 21:35:02 +00001747 unsigned NumHandlers = RawHandlers.size();
1748 assert(NumHandlers > 0 &&
1749 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00001750 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00001751
Sebastian Redlc447aba2009-07-29 17:15:45 +00001752 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00001753
1754 for (unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl8351da02008-12-22 21:35:02 +00001755 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00001756 if (!Handler->getExceptionDecl()) {
1757 if (i < NumHandlers - 1)
1758 return StmtError(Diag(Handler->getLocStart(),
1759 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Sebastian Redlc447aba2009-07-29 17:15:45 +00001761 continue;
1762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Sebastian Redlc447aba2009-07-29 17:15:45 +00001764 const QualType CaughtType = Handler->getCaughtType();
1765 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1766 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00001767 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00001768
1769 // Detect handlers for the same type as an earlier one.
1770 if (NumHandlers > 1) {
1771 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Sebastian Redlc447aba2009-07-29 17:15:45 +00001773 TypeWithHandler prev = TypesWithHandlers[0];
1774 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1775 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Sebastian Redlc447aba2009-07-29 17:15:45 +00001777 if (curr == prev) {
1778 Diag(curr.getTypeSpecStartLoc(),
1779 diag::warn_exception_caught_by_earlier_handler)
1780 << curr.getCatchStmt()->getCaughtType().getAsString();
1781 Diag(prev.getTypeSpecStartLoc(),
1782 diag::note_previous_exception_handler)
1783 << prev.getCatchStmt()->getCaughtType().getAsString();
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Sebastian Redlc447aba2009-07-29 17:15:45 +00001786 prev = curr;
1787 }
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
John McCall781472f2010-08-25 08:40:02 +00001790 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00001791
Sebastian Redl8351da02008-12-22 21:35:02 +00001792 // FIXME: We should detect handlers that cannot catch anything because an
1793 // earlier handler catches a superclass. Need to find a method that is not
1794 // quadratic for this.
1795 // Neither of these are explicitly forbidden, but every compiler detects them
1796 // and warns.
1797
John McCall9ae2f072010-08-23 23:25:46 +00001798 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00001799 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00001800}