blob: 6dcfbbab84740976db6849148142898b3f2b19d1 [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"
Richard Smithad762fc2011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Anders Carlsson51fe9962008-11-22 21:04:56 +000019#include "clang/AST/APValue.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000023#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000024#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
John McCall209acbd2010-04-06 22:24:14 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000027#include "clang/Lex/Preprocessor.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000028#include "clang/Basic/TargetInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000029#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000033using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000034
John McCall60d7b3a2010-08-24 06:29:42 +000035StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000036 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000037 if (!E) // FIXME: FullExprArg has no error state?
38 return StmtError();
39
Chris Lattner834a72a2008-07-25 23:18:17 +000040 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41 // void expression for its side effects. Conversion to void allows any
42 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000043
Chris Lattner834a72a2008-07-25 23:18:17 +000044 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000045 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000046}
47
48
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000049StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000050 bool HasLeadingEmptyMacro) {
51 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000052}
53
Chris Lattner337e5502011-02-18 01:27:55 +000054StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000056 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000057
Chris Lattner20401692009-04-12 20:13:14 +000058 // If we have an invalid decl, just return an error.
59 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner24e1e702009-03-04 04:23:07 +000061 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000062}
63
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000064void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000066
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000067 // If we have an invalid decl, just return.
68 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000069 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000071 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000072 var->setUsed();
73
John McCall7acddac2011-06-17 06:42:21 +000074 // foreach variables are never actually initialized in the way that
75 // the parser came up with.
76 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000077
John McCall7acddac2011-06-17 06:42:21 +000078 // In ARC, we don't need to retain the iteration variable of a fast
79 // enumeration loop. Rather than actually trying to catch that
80 // during declaration processing, we remove the consequences here.
81 if (getLangOptions().ObjCAutoRefCount) {
82 QualType type = var->getType();
83
84 // Only do this if we inferred the lifetime. Inferred lifetime
85 // will show up as a local qualifier because explicit lifetime
86 // should have shown up as an AttributedType instead.
87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
88 // Add 'const' and mark the variable as pseudo-strong.
89 var->setType(type.withConst());
90 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000091 }
92 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000093}
94
Chandler Carruthec8058f2011-08-17 09:34:37 +000095/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +000096///
97/// Adding a cast to void (or other expression wrappers) will prevent the
98/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +000099static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000100 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000101 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000102
103 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
104 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000105 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000106
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000107 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000108 IsNotEqual = Op->getOpcode() == BO_NE;
109 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
111 if (Op->getOperator() != OO_EqualEqual &&
112 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000113 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000114
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000115 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000116 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
117 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 } else {
119 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000120 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121 }
122
123 // Suppress warnings when the operator, suspicious as it may be, comes from
124 // a macro expansion.
125 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000126 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000127
Chandler Carruthec8058f2011-08-17 09:34:37 +0000128 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000129 << (unsigned)IsNotEqual << E->getSourceRange();
130
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000131 // If the LHS is a plausible entity to assign to, provide a fixit hint to
132 // correct common typos.
133 if (CanAssign) {
134 if (IsNotEqual)
135 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
136 << FixItHint::CreateReplacement(Loc, "|=");
137 else
138 S.Diag(Loc, diag::note_equality_comparison_to_assign)
139 << FixItHint::CreateReplacement(Loc, "=");
140 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000141
142 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000143}
144
Anders Carlsson636463e2009-07-30 22:17:18 +0000145void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000146 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
147 return DiagnoseUnusedExprResult(Label->getSubStmt());
148
Anders Carlsson75443112009-07-30 22:39:03 +0000149 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000150 if (!E)
151 return;
152
Anders Carlsson636463e2009-07-30 22:17:18 +0000153 SourceLocation Loc;
154 SourceRange R1, R2;
Mike Stumpdf317bf2009-11-03 23:25:48 +0000155 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000156 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner419cfb32009-08-16 16:57:27 +0000158 // Okay, we have an unused result. Depending on what the base expression is,
159 // we might want to make a more specific diagnostic. Check for one of these
160 // cases now.
161 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000162 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000163 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000164 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
165 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000166
Chandler Carruthec8058f2011-08-17 09:34:37 +0000167 if (DiagnoseUnusedComparison(*this, E))
168 return;
169
John McCallf6a16482010-12-04 03:47:34 +0000170 E = E->IgnoreParenImpCasts();
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000171 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000172 if (E->getType()->isVoidType())
173 return;
174
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000175 // If the callee has attribute pure, const, or warn_unused_result, warn with
176 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000177 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000178 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000179 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000180 return;
181 }
182 if (FD->getAttr<PureAttr>()) {
183 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
184 return;
185 }
186 if (FD->getAttr<ConstAttr>()) {
187 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
188 return;
189 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000190 }
John McCall12f78a62010-12-02 01:19:52 +0000191 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
John McCallf85e1932011-06-15 23:02:42 +0000192 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
193 Diag(Loc, diag::err_arc_unused_init_message) << R1;
194 return;
195 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000196 const ObjCMethodDecl *MD = ME->getMethodDecl();
197 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000198 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000199 return;
200 }
John McCall12f78a62010-12-02 01:19:52 +0000201 } else if (isa<ObjCPropertyRefExpr>(E)) {
202 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000203 } else if (const CXXFunctionalCastExpr *FC
204 = dyn_cast<CXXFunctionalCastExpr>(E)) {
205 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
206 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
207 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000208 }
John McCall209acbd2010-04-06 22:24:14 +0000209 // Diagnose "(void*) blah" as a typo for "(void) blah".
210 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
211 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
212 QualType T = TI->getType();
213
214 // We really do want to use the non-canonical type here.
215 if (T == Context.VoidPtrTy) {
216 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
217
218 Diag(Loc, diag::warn_unused_voidptr)
219 << FixItHint::CreateRemoval(TL.getStarLoc());
220 return;
221 }
222 }
223
Ted Kremenek351ba912011-02-23 01:52:04 +0000224 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000225}
226
John McCall60d7b3a2010-08-24 06:29:42 +0000227StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000228Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000229 MultiStmtArg elts, bool isStmtExpr) {
230 unsigned NumElts = elts.size();
231 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000232 // If we're in C89 mode, check that we don't have any decls after stmts. If
233 // so, emit an extension diagnostic.
234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
235 // Note that __extension__ can be around a decl.
236 unsigned i = 0;
237 // Skip over all declarations.
238 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
239 /*empty*/;
240
241 // We found the end of the list or a statement. Scan for another declstmt.
242 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
243 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000245 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000246 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000247 Diag(D->getLocation(), diag::ext_mixed_decls_code);
248 }
249 }
Chris Lattner98414c12007-08-31 21:49:55 +0000250 // Warn about unused expressions in statements.
251 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000252 // Ignore statements that are last in a statement expression.
253 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000254 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Anders Carlsson636463e2009-07-30 22:17:18 +0000256 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000257 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000258
Ted Kremenek8189cde2009-02-07 01:47:29 +0000259 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000260}
261
John McCall60d7b3a2010-08-24 06:29:42 +0000262StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000263Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
264 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000265 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000266 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000267
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // C99 6.8.4.2p3: The expression shall be an integer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000269 // However, GCC allows any evaluatable integer expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000270 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
Douglas Gregordbb26db2009-05-15 23:57:33 +0000271 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner24e1e702009-03-04 04:23:07 +0000272 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000273
Chris Lattner6c36be52007-07-18 02:28:47 +0000274 // GCC extension: The expression shall be an integer constant.
Sebastian Redl117054a2008-12-28 16:13:43 +0000275
Douglas Gregordbb26db2009-05-15 23:57:33 +0000276 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
277 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000278 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl117054a2008-12-28 16:13:43 +0000279 }
280
John McCall781472f2010-08-25 08:40:02 +0000281 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000282 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000283 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000284 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
Douglas Gregordbb26db2009-05-15 23:57:33 +0000286 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
287 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000288 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000289 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000290}
291
Chris Lattner24e1e702009-03-04 04:23:07 +0000292/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000293void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000294 DiagnoseUnusedExprResult(SubStmt);
295
Chris Lattner24e1e702009-03-04 04:23:07 +0000296 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000297 CS->setSubStmt(SubStmt);
298}
299
John McCall60d7b3a2010-08-24 06:29:42 +0000300StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000301Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000302 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000303 DiagnoseUnusedExprResult(SubStmt);
304
John McCall781472f2010-08-25 08:40:02 +0000305 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000306 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000307 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000308 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000309
Douglas Gregordbb26db2009-05-15 23:57:33 +0000310 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000311 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000312 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000313}
314
John McCall60d7b3a2010-08-24 06:29:42 +0000315StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000316Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
317 SourceLocation ColonLoc, Stmt *SubStmt) {
318
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000319 // If the label was multiply defined, reject it now.
320 if (TheDecl->getStmt()) {
321 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
322 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000323 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 }
Sebastian Redlde307472009-01-11 00:38:46 +0000325
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000326 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000327 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
328 TheDecl->setStmt(LS);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000329 if (!TheDecl->isGnuLocal())
330 TheDecl->setLocation(IdentLoc);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000331 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000332}
333
John McCall60d7b3a2010-08-24 06:29:42 +0000334StmtResult
John McCalld226f652010-08-21 09:40:31 +0000335Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000336 Stmt *thenStmt, SourceLocation ElseLoc,
337 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000338 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000340 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000341 if (CondVar) {
342 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000343 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000344 if (CondResult.isInvalid())
345 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000346 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000347 Expr *ConditionExpr = CondResult.takeAs<Expr>();
348 if (!ConditionExpr)
349 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350
Anders Carlsson75443112009-07-30 22:39:03 +0000351 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000353 // Warn if the if block has a null body without an else value.
354 // this helps prevent bugs due to typos, such as
355 // if (condition);
356 // do_stuff();
Ted Kremenekb3198172010-09-16 00:37:05 +0000357 //
John McCall9ae2f072010-08-23 23:25:46 +0000358 if (!elseStmt) {
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000359 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
Argyrios Kyrtzidisa25b6a42010-11-19 20:54:25 +0000360 // But do not warn if the body is a macro that expands to nothing, e.g:
361 //
362 // #define CALL(x)
363 // if (condition)
364 // CALL(0);
365 //
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000366 if (!stmt->hasLeadingEmptyMacro())
Ted Kremenekb3198172010-09-16 00:37:05 +0000367 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000368 }
369
Anders Carlsson75443112009-07-30 22:39:03 +0000370 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000372 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000373 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000374}
375
Chris Lattnerf4021e72007-08-23 05:46:52 +0000376/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
377/// the specified width and sign. If an overflow occurs, detect it and emit
378/// the specified diagnostic.
379void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
380 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000381 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000382 unsigned DiagID) {
383 // Perform a conversion to the promoted condition type if needed.
384 if (NewWidth > Val.getBitWidth()) {
385 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000386 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000387 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000388
389 // If the input was signed and negative and the output is
390 // unsigned, don't bother to warn: this is implementation-defined
391 // behavior.
392 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000393 } else if (NewWidth < Val.getBitWidth()) {
394 // If this is a truncation, check for overflow.
395 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000396 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000397 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000398 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000399 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000400 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000401 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattnerf4021e72007-08-23 05:46:52 +0000403 // Regardless of whether a diagnostic was emitted, really do the
404 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000405 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000406 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000407 } else if (NewSign != Val.isSigned()) {
408 // Convert the sign to match the sign of the condition. This can cause
409 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000410 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000411 // behavior.
412 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000413 llvm::APSInt OldVal(Val);
414 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000415 }
416}
417
Chris Lattner0471f5b2007-08-23 18:29:20 +0000418namespace {
419 struct CaseCompareFunctor {
420 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
421 const llvm::APSInt &RHS) {
422 return LHS.first < RHS;
423 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000424 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
425 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
426 return LHS.first < RHS.first;
427 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000428 bool operator()(const llvm::APSInt &LHS,
429 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
430 return LHS < RHS.first;
431 }
432 };
433}
434
Chris Lattner764a7ce2007-09-21 18:15:22 +0000435/// CmpCaseVals - Comparison predicate for sorting case values.
436///
437static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
438 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
439 if (lhs.first < rhs.first)
440 return true;
441
442 if (lhs.first == rhs.first &&
443 lhs.second->getCaseLoc().getRawEncoding()
444 < rhs.second->getCaseLoc().getRawEncoding())
445 return true;
446 return false;
447}
448
Douglas Gregorba915af2010-02-08 22:24:16 +0000449/// CmpEnumVals - Comparison predicate for sorting enumeration values.
450///
451static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
452 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
453{
454 return lhs.first < rhs.first;
455}
456
457/// EqEnumVals - Comparison preficate for uniqing enumeration values.
458///
459static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
460 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
461{
462 return lhs.first == rhs.first;
463}
464
Chris Lattner5f048812009-10-16 16:45:22 +0000465/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
466/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000467static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
468 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
469 expr = cleanups->getSubExpr();
470 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
471 if (impcast->getCastKind() != CK_IntegralCast) break;
472 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000473 }
474 return expr->getType();
475}
476
John McCall60d7b3a2010-08-24 06:29:42 +0000477StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000478Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000479 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000480 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000481
Douglas Gregor586596f2010-05-06 17:25:47 +0000482 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000483 if (CondVar) {
484 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000485 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
486 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000487 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488
John McCall9ae2f072010-08-23 23:25:46 +0000489 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000490 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000491
John McCall9ae2f072010-08-23 23:25:46 +0000492 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000493 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000494
John McCall3c3b7f92011-10-25 17:37:35 +0000495 CondResult = CheckPlaceholderExpr(Cond);
496 if (CondResult.isInvalid())
497 return StmtError();
498
John McCall9ae2f072010-08-23 23:25:46 +0000499 CondResult
Fariborz Jahanian9c1ba402011-10-27 20:06:32 +0000500 = ConvertToIntegralOrEnumerationType(SwitchLoc, CondResult.take(),
Douglas Gregorc30614b2010-06-29 23:17:37 +0000501 PDiag(diag::err_typecheck_statement_requires_integer),
502 PDiag(diag::err_switch_incomplete_class_type)
John McCall9ae2f072010-08-23 23:25:46 +0000503 << Cond->getSourceRange(),
Douglas Gregorc30614b2010-06-29 23:17:37 +0000504 PDiag(diag::err_switch_explicit_conversion),
505 PDiag(diag::note_switch_conversion),
506 PDiag(diag::err_switch_multiple_conversions),
Douglas Gregor6bc574d2010-06-30 00:20:43 +0000507 PDiag(diag::note_switch_conversion),
508 PDiag(0));
John McCall9ae2f072010-08-23 23:25:46 +0000509 if (CondResult.isInvalid()) return StmtError();
510 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000511
John McCalla8e0cd82011-08-06 07:30:58 +0000512 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
513 CondResult = UsualUnaryConversions(Cond);
514 if (CondResult.isInvalid()) return StmtError();
515 Cond = CondResult.take();
516
John McCalld226f652010-08-21 09:40:31 +0000517 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000518 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000519 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000520 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000521 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000522 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000523 }
John McCallb60a77e2010-08-01 00:26:45 +0000524
John McCall781472f2010-08-25 08:40:02 +0000525 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526
John McCall9ae2f072010-08-23 23:25:46 +0000527 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000528 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000529 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000530}
531
Gabor Greif28164ab2010-10-01 22:05:14 +0000532static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
533 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000534 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000535 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000536 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000537 Val.setIsSigned(IsSigned);
538}
539
John McCall60d7b3a2010-08-24 06:29:42 +0000540StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000541Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
542 Stmt *BodyStmt) {
543 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000544 assert(SS == getCurFunction()->SwitchStack.back() &&
545 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000546
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000547 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000548 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000549
Chris Lattnerf4021e72007-08-23 05:46:52 +0000550 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000551 if (!CondExpr) return StmtError();
552
553 QualType CondType = CondExpr->getType();
554
John McCall0fb97082010-05-18 03:19:21 +0000555 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000556 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000557 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000558
Chris Lattner5f048812009-10-16 16:45:22 +0000559 // C++ 6.4.2.p2:
560 // Integral promotions are performed (on the switch condition).
561 //
562 // A case value unrepresentable by the original switch condition
563 // type (before the promotion) doesn't make sense, even when it can
564 // be represented by the promoted type. Therefore we need to find
565 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000566 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000567 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000569 // appropriate type now, just return an error.
570 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000571 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000572
Chris Lattner2b334bb2010-04-16 23:34:13 +0000573 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000574 // switch(bool_expr) {...} is often a programmer error, e.g.
575 // switch(n && mask) { ... } // Doh - should be "n & mask".
576 // One can always use an if statement instead of switch(bool_expr).
577 Diag(SwitchLoc, diag::warn_bool_switch_condition)
578 << CondExpr->getSourceRange();
579 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000580 }
Sebastian Redlde307472009-01-11 00:38:46 +0000581
Chris Lattnerf4021e72007-08-23 05:46:52 +0000582 // Get the bitwidth of the switched-on value before promotions. We must
583 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000584 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000585 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000586 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000587 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000588 bool CondIsSigned
589 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattnerf4021e72007-08-23 05:46:52 +0000591 // Accumulate all of the case values in a vector so that we can sort them
592 // and detect duplicates. This vector contains the APInt for the case after
593 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000594 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000595 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattnerf4021e72007-08-23 05:46:52 +0000597 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000598 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
599 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattnerf4021e72007-08-23 05:46:52 +0000601 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000603 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Douglas Gregordbb26db2009-05-15 23:57:33 +0000605 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000606 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000608 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000609 if (TheDefaultStmt) {
610 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000611 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000612
Chris Lattnerf4021e72007-08-23 05:46:52 +0000613 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000614 // we'll return a valid AST. This requires recursing down the AST and
615 // finding it, not something we are set up to do right now. For now,
616 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000617 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000618 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000619 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattnerf4021e72007-08-23 05:46:52 +0000621 } else {
622 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerf4021e72007-08-23 05:46:52 +0000624 // We already verified that the expression has a i-c-e value (C99
625 // 6.8.4.2p3) - get that value now.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000626 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000627
628 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
629 HasDependentValue = true;
630 break;
631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000633 llvm::APSInt LoVal = Lo->EvaluateKnownConstInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattnerf4021e72007-08-23 05:46:52 +0000635 // Convert the value to the same width/sign as the condition.
636 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000637 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000638 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000639
Chris Lattner1e0a3902008-01-16 19:17:22 +0000640 // If the LHS is not the same type as the condition, insert an implicit
641 // cast.
Richard Smith4f870622011-10-27 22:11:44 +0000642 // FIXME: In C++11, the value is a converted constant expression of the
643 // promoted type of the switch condition.
644 Lo = DefaultLvalueConversion(Lo).take();
John Wiegley429bb272011-04-08 18:41:53 +0000645 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
Chris Lattner1e0a3902008-01-16 19:17:22 +0000646 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000648 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000649 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000650 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000651 CS->getRHS()->isValueDependent()) {
652 HasDependentValue = true;
653 break;
654 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000655 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000656 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000657 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000658 }
659 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000660
661 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000662 // If we don't have a default statement, check whether the
663 // condition is constant.
664 llvm::APSInt ConstantCondValue;
665 bool HasConstantCond = false;
666 bool ShouldCheckConstantCond = false;
667 if (!HasDependentValue && !TheDefaultStmt) {
668 Expr::EvalResult Result;
669 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
670 if (HasConstantCond) {
671 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
672 ConstantCondValue = Result.Val.getInt();
673 ShouldCheckConstantCond = true;
674
675 assert(ConstantCondValue.getBitWidth() == CondWidth &&
676 ConstantCondValue.isSigned() == CondIsSigned);
677 }
678 }
679
Douglas Gregordbb26db2009-05-15 23:57:33 +0000680 // Sort all the scalar case values so we can easily detect duplicates.
681 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
682
683 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000684 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
685 if (ShouldCheckConstantCond &&
686 CaseVals[i].first == ConstantCondValue)
687 ShouldCheckConstantCond = false;
688
689 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000690 // If we have a duplicate, report it.
Mike Stump1eb44332009-09-09 15:08:12 +0000691 Diag(CaseVals[i].second->getLHS()->getLocStart(),
John McCall0fb97082010-05-18 03:19:21 +0000692 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
693 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000694 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000695 // FIXME: We really want to remove the bogus case stmt from the
696 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000697 CaseListIsErroneous = true;
698 }
699 }
700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Douglas Gregordbb26db2009-05-15 23:57:33 +0000702 // Detect duplicate case ranges, which usually don't exist at all in
703 // the first place.
704 if (!CaseRanges.empty()) {
705 // Sort all the case ranges by their low value so we can easily detect
706 // overlaps between ranges.
707 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Douglas Gregordbb26db2009-05-15 23:57:33 +0000709 // Scan the ranges, computing the high values and removing empty ranges.
710 std::vector<llvm::APSInt> HiVals;
711 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000712 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000713 CaseStmt *CR = CaseRanges[i].second;
714 Expr *Hi = CR->getRHS();
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000715 llvm::APSInt HiVal = Hi->EvaluateKnownConstInt(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Douglas Gregordbb26db2009-05-15 23:57:33 +0000717 // Convert the value to the same width/sign as the condition.
718 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000719 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000720 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Richard Smith4f870622011-10-27 22:11:44 +0000722 // If the RHS is not the same type as the condition, insert an implicit
Douglas Gregordbb26db2009-05-15 23:57:33 +0000723 // cast.
Richard Smith4f870622011-10-27 22:11:44 +0000724 // FIXME: In C++11, the value is a converted constant expression of the
725 // promoted type of the switch condition.
726 Hi = DefaultLvalueConversion(Hi).take();
John Wiegley429bb272011-04-08 18:41:53 +0000727 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000728 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregordbb26db2009-05-15 23:57:33 +0000730 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000731 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000732 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
733 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000734 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000735 CaseRanges.erase(CaseRanges.begin()+i);
736 --i, --e;
737 continue;
738 }
John McCall0fb97082010-05-18 03:19:21 +0000739
740 if (ShouldCheckConstantCond &&
741 LoVal <= ConstantCondValue &&
742 ConstantCondValue <= HiVal)
743 ShouldCheckConstantCond = false;
744
Douglas Gregordbb26db2009-05-15 23:57:33 +0000745 HiVals.push_back(HiVal);
746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Douglas Gregordbb26db2009-05-15 23:57:33 +0000748 // Rescan the ranges, looking for overlap with singleton values and other
749 // ranges. Since the range list is sorted, we only need to compare case
750 // ranges with their neighbors.
751 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
752 llvm::APSInt &CRLo = CaseRanges[i].first;
753 llvm::APSInt &CRHi = HiVals[i];
754 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregordbb26db2009-05-15 23:57:33 +0000756 // Check to see whether the case range overlaps with any
757 // singleton cases.
758 CaseStmt *OverlapStmt = 0;
759 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Douglas Gregordbb26db2009-05-15 23:57:33 +0000761 // Find the smallest value >= the lower bound. If I is in the
762 // case range, then we have overlap.
763 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
764 CaseVals.end(), CRLo,
765 CaseCompareFunctor());
766 if (I != CaseVals.end() && I->first < CRHi) {
767 OverlapVal = I->first; // Found overlap with scalar.
768 OverlapStmt = I->second;
769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Douglas Gregordbb26db2009-05-15 23:57:33 +0000771 // Find the smallest value bigger than the upper bound.
772 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
773 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
774 OverlapVal = (I-1)->first; // Found overlap with scalar.
775 OverlapStmt = (I-1)->second;
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Douglas Gregordbb26db2009-05-15 23:57:33 +0000778 // Check to see if this case stmt overlaps with the subsequent
779 // case range.
780 if (i && CRLo <= HiVals[i-1]) {
781 OverlapVal = HiVals[i-1]; // Found overlap with range.
782 OverlapStmt = CaseRanges[i-1].second;
783 }
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregordbb26db2009-05-15 23:57:33 +0000785 if (OverlapStmt) {
786 // If we have a duplicate, report it.
787 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
788 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000789 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000790 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000791 // FIXME: We really want to remove the bogus case stmt from the
792 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000793 CaseListIsErroneous = true;
794 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000795 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000796 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000797
John McCall0fb97082010-05-18 03:19:21 +0000798 // Complain if we have a constant condition and we didn't find a match.
799 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
800 // TODO: it would be nice if we printed enums as enums, chars as
801 // chars, etc.
802 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
803 << ConstantCondValue.toString(10)
804 << CondExpr->getSourceRange();
805 }
806
807 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000808 // values. We only issue a warning if there is not 'default:', but
809 // we still do the analysis to preserve this information in the AST
810 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000811 //
Chris Lattnerce784612010-09-16 17:09:42 +0000812 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000813
Douglas Gregorba915af2010-02-08 22:24:16 +0000814 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000815 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000816 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000817 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000818 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000819 EnumValsTy EnumVals;
820
John McCall0fb97082010-05-18 03:19:21 +0000821 // Gather all enum values, set their type and sort them,
822 // allowing easier comparison with CaseVals.
823 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000824 EDI != ED->enumerator_end(); ++EDI) {
825 llvm::APSInt Val = EDI->getInitVal();
826 AdjustAPSInt(Val, CondWidth, CondIsSigned);
827 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000828 }
829 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000830 EnumValsTy::iterator EIend =
831 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000832
833 // See which case values aren't in enum.
834 // TODO: we might want to check whether case values are out of the
835 // enum even if we don't want to check whether all cases are handled.
836 if (!TheDefaultStmt) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000837 EnumValsTy::const_iterator EI = EnumVals.begin();
838 for (CaseValsTy::const_iterator CI = CaseVals.begin();
John McCall0fb97082010-05-18 03:19:21 +0000839 CI != CaseVals.end(); CI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000840 while (EI != EIend && EI->first < CI->first)
841 EI++;
842 if (EI == EIend || EI->first > CI->first)
John McCall0fb97082010-05-18 03:19:21 +0000843 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
844 << ED->getDeclName();
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000845 }
846 // See which of case ranges aren't in enum
847 EI = EnumVals.begin();
848 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
John McCall0fb97082010-05-18 03:19:21 +0000849 RI != CaseRanges.end() && EI != EIend; RI++) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000850 while (EI != EIend && EI->first < RI->first)
851 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000852
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000853 if (EI == EIend || EI->first != RI->first) {
854 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
855 << ED->getDeclName();
856 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000857
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000858 llvm::APSInt Hi =
859 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +0000860 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000861 while (EI != EIend && EI->first < Hi)
862 EI++;
863 if (EI == EIend || EI->first != Hi)
864 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
865 << ED->getDeclName();
866 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000867 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000868
Ted Kremenek559fb552010-09-09 00:05:53 +0000869 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000870 CaseValsTy::const_iterator CI = CaseVals.begin();
871 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000872 bool hasCasesNotInSwitch = false;
873
Chris Lattner5f9e2722011-07-23 10:55:15 +0000874 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000875
Ted Kremenek559fb552010-09-09 00:05:53 +0000876 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000877 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000878 llvm::APSInt CIVal;
879 while (CI != CaseVals.end() && CI->first < EI->first)
880 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000881
Douglas Gregorba915af2010-02-08 22:24:16 +0000882 if (CI != CaseVals.end() && CI->first == EI->first)
883 continue;
884
Ted Kremenek559fb552010-09-09 00:05:53 +0000885 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +0000886 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000887 llvm::APSInt Hi =
888 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +0000889 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +0000890 if (EI->first <= Hi)
891 break;
892 }
893
Ted Kremenek559fb552010-09-09 00:05:53 +0000894 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000895 hasCasesNotInSwitch = true;
896 if (!TheDefaultStmt)
Chris Lattnerce784612010-09-16 17:09:42 +0000897 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000898 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000899 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000900
Chris Lattnerce784612010-09-16 17:09:42 +0000901 // Produce a nice diagnostic if multiple values aren't handled.
902 switch (UnhandledNames.size()) {
903 case 0: break;
904 case 1:
905 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
906 << UnhandledNames[0];
907 break;
908 case 2:
909 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
910 << UnhandledNames[0] << UnhandledNames[1];
911 break;
912 case 3:
913 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
914 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
915 break;
916 default:
917 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
918 << (unsigned)UnhandledNames.size()
919 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
920 break;
921 }
Ted Kremenek559fb552010-09-09 00:05:53 +0000922
923 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000924 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +0000925 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000926 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000927
Mike Stump390b4cc2009-05-16 07:39:55 +0000928 // FIXME: If the case list was broken is some way, we don't have a good system
929 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000930 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +0000931 return StmtError();
932
Sebastian Redlde307472009-01-11 00:38:46 +0000933 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000934}
935
John McCall60d7b3a2010-08-24 06:29:42 +0000936StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000937Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +0000938 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +0000939 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000940
Douglas Gregor5656e142009-11-24 21:15:44 +0000941 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000942 if (CondVar) {
943 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000944 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000945 if (CondResult.isInvalid())
946 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +0000947 }
John McCall9ae2f072010-08-23 23:25:46 +0000948 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000949 if (!ConditionExpr)
950 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000951
John McCall9ae2f072010-08-23 23:25:46 +0000952 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000954 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +0000955 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000956}
957
John McCall60d7b3a2010-08-24 06:29:42 +0000958StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000959Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +0000960 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +0000961 Expr *Cond, SourceLocation CondRParen) {
962 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +0000963
John Wiegley429bb272011-04-08 18:41:53 +0000964 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
965 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +0000966 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +0000967 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000968
John McCallb4eb64d2010-10-08 02:01:28 +0000969 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +0000970 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000971 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000972 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000973 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000974
John McCall9ae2f072010-08-23 23:25:46 +0000975 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +0000976
John McCall9ae2f072010-08-23 23:25:46 +0000977 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +0000978}
979
John McCall60d7b3a2010-08-24 06:29:42 +0000980StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +0000981Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000982 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000983 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +0000984 SourceLocation RParenLoc, Stmt *Body) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000985 if (!getLangOptions().CPlusPlus) {
986 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000987 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
988 // declare identifiers for objects having storage class 'auto' or
989 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000990 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
991 DI!=DE; ++DI) {
992 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +0000993 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000994 VD = 0;
995 if (VD == 0)
996 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
997 // FIXME: mark decl erroneous!
998 }
Chris Lattnerae3b7012007-08-28 05:03:08 +0000999 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001001
John McCall60d7b3a2010-08-24 06:29:42 +00001002 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001003 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001004 if (secondVar) {
1005 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001006 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001007 if (SecondResult.isInvalid())
1008 return StmtError();
1009 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001010
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001011 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001012
Anders Carlsson3af708f2009-08-01 01:39:59 +00001013 DiagnoseUnusedExprResult(First);
1014 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001015 DiagnoseUnusedExprResult(Body);
1016
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017 return Owned(new (Context) ForStmt(Context, First,
1018 SecondResult.take(), ConditionVar,
1019 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001020 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001021}
1022
John McCallf6a16482010-12-04 03:47:34 +00001023/// In an Objective C collection iteration statement:
1024/// for (x in y)
1025/// x can be an arbitrary l-value expression. Bind it up as a
1026/// full-expression.
1027StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1028 CheckImplicitConversions(E);
John McCall4765fa02010-12-06 08:20:24 +00001029 ExprResult Result = MaybeCreateExprWithCleanups(E);
John McCallf6a16482010-12-04 03:47:34 +00001030 if (Result.isInvalid()) return StmtError();
1031 return Owned(static_cast<Stmt*>(Result.get()));
1032}
1033
John McCall990567c2011-07-27 01:07:15 +00001034ExprResult
1035Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1036 assert(collection);
1037
1038 // Bail out early if we've got a type-dependent expression.
1039 if (collection->isTypeDependent()) return Owned(collection);
1040
1041 // Perform normal l-value conversion.
1042 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1043 if (result.isInvalid())
1044 return ExprError();
1045 collection = result.take();
1046
1047 // The operand needs to have object-pointer type.
1048 // TODO: should we do a contextual conversion?
1049 const ObjCObjectPointerType *pointerType =
1050 collection->getType()->getAs<ObjCObjectPointerType>();
1051 if (!pointerType)
1052 return Diag(forLoc, diag::err_collection_expr_type)
1053 << collection->getType() << collection->getSourceRange();
1054
1055 // Check that the operand provides
1056 // - countByEnumeratingWithState:objects:count:
1057 const ObjCObjectType *objectType = pointerType->getObjectType();
1058 ObjCInterfaceDecl *iface = objectType->getInterface();
1059
1060 // If we have a forward-declared type, we can't do this check.
1061 if (iface && iface->isForwardDecl()) {
1062 // This is ill-formed under ARC.
1063 if (getLangOptions().ObjCAutoRefCount) {
1064 Diag(forLoc, diag::err_arc_collection_forward)
1065 << pointerType->getPointeeType() << collection->getSourceRange();
1066 }
1067
1068 // Otherwise, if we have any useful type information, check that
1069 // the type declares the appropriate method.
1070 } else if (iface || !objectType->qual_empty()) {
1071 IdentifierInfo *selectorIdents[] = {
1072 &Context.Idents.get("countByEnumeratingWithState"),
1073 &Context.Idents.get("objects"),
1074 &Context.Idents.get("count")
1075 };
1076 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1077
1078 ObjCMethodDecl *method = 0;
1079
1080 // If there's an interface, look in both the public and private APIs.
1081 if (iface) {
1082 method = iface->lookupInstanceMethod(selector);
1083 if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1084 }
1085
1086 // Also check protocol qualifiers.
1087 if (!method)
1088 method = LookupMethodInQualifiedType(selector, pointerType,
1089 /*instance*/ true);
1090
1091 // If we didn't find it anywhere, give up.
1092 if (!method) {
1093 Diag(forLoc, diag::warn_collection_expr_type)
1094 << collection->getType() << selector << collection->getSourceRange();
1095 }
1096
1097 // TODO: check for an incompatible signature?
1098 }
1099
1100 // Wrap up any cleanups in the expression.
1101 return Owned(MaybeCreateExprWithCleanups(collection));
1102}
1103
John McCall60d7b3a2010-08-24 06:29:42 +00001104StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001105Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1106 SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001107 Stmt *First, Expr *Second,
1108 SourceLocation RParenLoc, Stmt *Body) {
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001109 if (First) {
1110 QualType FirstType;
1111 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001112 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001113 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1114 diag::err_toomany_element_decls));
1115
John McCallf85e1932011-06-15 23:02:42 +00001116 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1117 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001118 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1119 // declare identifiers for objects having storage class 'auto' or
1120 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001121 if (!D->hasLocalStorage())
1122 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001123 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001124 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001125 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001126 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001127 return StmtError(Diag(First->getLocStart(),
1128 diag::err_selector_element_not_lvalue)
1129 << First->getSourceRange());
1130
Mike Stump1eb44332009-09-09 15:08:12 +00001131 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001132 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001133 if (!FirstType->isDependentType() &&
1134 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001135 !FirstType->isBlockPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001136 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00001137 << FirstType << First->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001138 }
John McCall990567c2011-07-27 01:07:15 +00001139
Ted Kremenek8189cde2009-02-07 01:47:29 +00001140 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1141 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001142}
Reid Spencer5f016e22007-07-11 17:01:13 +00001143
Richard Smithad762fc2011-04-14 22:09:26 +00001144namespace {
1145
1146enum BeginEndFunction {
1147 BEF_begin,
1148 BEF_end
1149};
1150
1151/// Build a variable declaration for a for-range statement.
1152static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1153 QualType Type, const char *Name) {
1154 DeclContext *DC = SemaRef.CurContext;
1155 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1156 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1157 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1158 TInfo, SC_Auto, SC_None);
Richard Smithb403d6d2011-04-18 15:49:25 +00001159 Decl->setImplicit();
Richard Smithad762fc2011-04-14 22:09:26 +00001160 return Decl;
1161}
1162
1163/// Finish building a variable declaration for a for-range statement.
1164/// \return true if an error occurs.
1165static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1166 SourceLocation Loc, int diag) {
1167 // Deduce the type for the iterator variable now rather than leaving it to
1168 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1169 TypeSourceInfo *InitTSI = 0;
1170 if (Init->getType()->isVoidType() ||
1171 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1172 SemaRef.Diag(Loc, diag) << Init->getType();
1173 if (!InitTSI) {
1174 Decl->setInvalidDecl();
1175 return true;
1176 }
1177 Decl->setTypeSourceInfo(InitTSI);
1178 Decl->setType(InitTSI->getType());
1179
John McCallf85e1932011-06-15 23:02:42 +00001180 // In ARC, infer lifetime.
1181 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1182 // we're doing the equivalent of fast iteration.
1183 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1184 SemaRef.inferObjCARCLifetime(Decl))
1185 Decl->setInvalidDecl();
1186
Richard Smithad762fc2011-04-14 22:09:26 +00001187 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1188 /*TypeMayContainAuto=*/false);
1189 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001190 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001191 return false;
1192}
1193
1194/// Produce a note indicating which begin/end function was implicitly called
1195/// by a C++0x for-range statement. This is often not obvious from the code,
1196/// nor from the diagnostics produced when analysing the implicit expressions
1197/// required in a for-range statement.
1198void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1199 BeginEndFunction BEF) {
1200 CallExpr *CE = dyn_cast<CallExpr>(E);
1201 if (!CE)
1202 return;
1203 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1204 if (!D)
1205 return;
1206 SourceLocation Loc = D->getLocation();
1207
1208 std::string Description;
1209 bool IsTemplate = false;
1210 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1211 Description = SemaRef.getTemplateArgumentBindingsText(
1212 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1213 IsTemplate = true;
1214 }
1215
1216 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1217 << BEF << IsTemplate << Description << E->getType();
1218}
1219
1220/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1221/// given LookupResult is non-empty, it is assumed to describe a member which
1222/// will be invoked. Otherwise, the function will be found via argument
1223/// dependent lookup.
1224static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1225 SourceLocation Loc,
1226 VarDecl *Decl,
1227 BeginEndFunction BEF,
1228 const DeclarationNameInfo &NameInfo,
1229 LookupResult &MemberLookup,
1230 Expr *Range) {
1231 ExprResult CallExpr;
1232 if (!MemberLookup.empty()) {
1233 ExprResult MemberRef =
1234 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1235 /*IsPtr=*/false, CXXScopeSpec(),
1236 /*Qualifier=*/0, MemberLookup,
1237 /*TemplateArgs=*/0);
1238 if (MemberRef.isInvalid())
1239 return ExprError();
1240 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1241 Loc, 0);
1242 if (CallExpr.isInvalid())
1243 return ExprError();
1244 } else {
1245 UnresolvedSet<0> FoundNames;
1246 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1247 // std is an associated namespace.
1248 UnresolvedLookupExpr *Fn =
1249 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1250 NestedNameSpecifierLoc(), NameInfo,
1251 /*NeedsADL=*/true, /*Overloaded=*/false,
1252 FoundNames.begin(), FoundNames.end(),
1253 /*LookInStdNamespace=*/true);
1254 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1255 0);
1256 if (CallExpr.isInvalid()) {
1257 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1258 << Range->getType();
1259 return ExprError();
1260 }
1261 }
1262 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1263 diag::err_for_range_iter_deduction_failure)) {
1264 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1265 return ExprError();
1266 }
1267 return CallExpr;
1268}
1269
1270}
1271
1272/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1273///
1274/// C++0x [stmt.ranged]:
1275/// A range-based for statement is equivalent to
1276///
1277/// {
1278/// auto && __range = range-init;
1279/// for ( auto __begin = begin-expr,
1280/// __end = end-expr;
1281/// __begin != __end;
1282/// ++__begin ) {
1283/// for-range-declaration = *__begin;
1284/// statement
1285/// }
1286/// }
1287///
1288/// The body of the loop is not available yet, since it cannot be analysed until
1289/// we have determined the type of the for-range-declaration.
1290StmtResult
1291Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1292 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1293 SourceLocation RParenLoc) {
1294 if (!First || !Range)
1295 return StmtError();
1296
1297 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1298 assert(DS && "first part of for range not a decl stmt");
1299
1300 if (!DS->isSingleDecl()) {
1301 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1302 return StmtError();
1303 }
1304 if (DS->getSingleDecl()->isInvalidDecl())
1305 return StmtError();
1306
1307 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1308 return StmtError();
1309
1310 // Build auto && __range = range-init
1311 SourceLocation RangeLoc = Range->getLocStart();
1312 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1313 Context.getAutoRRefDeductType(),
1314 "__range");
1315 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1316 diag::err_for_range_deduction_failure))
1317 return StmtError();
1318
1319 // Claim the type doesn't contain auto: we've already done the checking.
1320 DeclGroupPtrTy RangeGroup =
1321 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1322 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1323 if (RangeDecl.isInvalid())
1324 return StmtError();
1325
1326 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1327 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1328 RParenLoc);
1329}
1330
1331/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1332StmtResult
1333Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1334 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1335 Expr *Inc, Stmt *LoopVarDecl,
1336 SourceLocation RParenLoc) {
1337 Scope *S = getCurScope();
1338
1339 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1340 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1341 QualType RangeVarType = RangeVar->getType();
1342
1343 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1344 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1345
1346 StmtResult BeginEndDecl = BeginEnd;
1347 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1348
1349 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1350 SourceLocation RangeLoc = RangeVar->getLocation();
1351
Ted Kremeneke50b0152011-10-10 22:36:28 +00001352 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1353
1354 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1355 VK_LValue, ColonLoc);
1356 if (BeginRangeRef.isInvalid())
1357 return StmtError();
1358
1359 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1360 VK_LValue, ColonLoc);
1361 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001362 return StmtError();
1363
1364 QualType AutoType = Context.getAutoDeductType();
1365 Expr *Range = RangeVar->getInit();
1366 if (!Range)
1367 return StmtError();
1368 QualType RangeType = Range->getType();
1369
1370 if (RequireCompleteType(RangeLoc, RangeType,
1371 PDiag(diag::err_for_range_incomplete_type)))
1372 return StmtError();
1373
1374 // Build auto __begin = begin-expr, __end = end-expr.
1375 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1376 "__begin");
1377 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1378 "__end");
1379
1380 // Build begin-expr and end-expr and attach to __begin and __end variables.
1381 ExprResult BeginExpr, EndExpr;
1382 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1383 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1384 // __range + __bound, respectively, where __bound is the array bound. If
1385 // _RangeT is an array of unknown size or an array of incomplete type,
1386 // the program is ill-formed;
1387
1388 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001389 BeginExpr = BeginRangeRef;
1390 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001391 diag::err_for_range_iter_deduction_failure)) {
1392 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1393 return StmtError();
1394 }
1395
1396 // Find the array bound.
1397 ExprResult BoundExpr;
1398 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1399 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001400 Context.getPointerDiffType(),
1401 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001402 else if (const VariableArrayType *VAT =
1403 dyn_cast<VariableArrayType>(UnqAT))
1404 BoundExpr = VAT->getSizeExpr();
1405 else {
1406 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1407 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001408 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001409 }
1410
1411 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001412 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001413 BoundExpr.get());
1414 if (EndExpr.isInvalid())
1415 return StmtError();
1416 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1417 diag::err_for_range_iter_deduction_failure)) {
1418 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1419 return StmtError();
1420 }
1421 } else {
1422 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1423 ColonLoc);
1424 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1425 ColonLoc);
1426
1427 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1428 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1429
1430 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1431 // - if _RangeT is a class type, the unqualified-ids begin and end are
1432 // looked up in the scope of class _RangeT as if by class member access
1433 // lookup (3.4.5), and if either (or both) finds at least one
1434 // declaration, begin-expr and end-expr are __range.begin() and
1435 // __range.end(), respectively;
1436 LookupQualifiedName(BeginMemberLookup, D);
1437 LookupQualifiedName(EndMemberLookup, D);
1438
1439 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1440 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1441 << RangeType << BeginMemberLookup.empty();
1442 return StmtError();
1443 }
1444 } else {
1445 // - otherwise, begin-expr and end-expr are begin(__range) and
1446 // end(__range), respectively, where begin and end are looked up with
1447 // argument-dependent lookup (3.4.2). For the purposes of this name
1448 // lookup, namespace std is an associated namespace.
1449 }
1450
1451 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1452 BEF_begin, BeginNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001453 BeginMemberLookup,
1454 BeginRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001455 if (BeginExpr.isInvalid())
1456 return StmtError();
1457
1458 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1459 BEF_end, EndNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001460 EndMemberLookup, EndRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001461 if (EndExpr.isInvalid())
1462 return StmtError();
1463 }
1464
1465 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1466 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1467 if (!Context.hasSameType(BeginType, EndType)) {
1468 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1469 << BeginType << EndType;
1470 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1471 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1472 }
1473
1474 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1475 // Claim the type doesn't contain auto: we've already done the checking.
1476 DeclGroupPtrTy BeginEndGroup =
1477 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1478 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1479
Ted Kremeneke50b0152011-10-10 22:36:28 +00001480 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1481 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001482 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001483 if (BeginRef.isInvalid())
1484 return StmtError();
1485
Richard Smithad762fc2011-04-14 22:09:26 +00001486 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1487 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001488 if (EndRef.isInvalid())
1489 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001490
1491 // Build and check __begin != __end expression.
1492 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1493 BeginRef.get(), EndRef.get());
1494 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1495 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1496 if (NotEqExpr.isInvalid()) {
1497 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1498 if (!Context.hasSameType(BeginType, EndType))
1499 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1500 return StmtError();
1501 }
1502
1503 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001504 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1505 VK_LValue, ColonLoc);
1506 if (BeginRef.isInvalid())
1507 return StmtError();
1508
Richard Smithad762fc2011-04-14 22:09:26 +00001509 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1510 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1511 if (IncrExpr.isInvalid()) {
1512 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1513 return StmtError();
1514 }
1515
1516 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001517 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1518 VK_LValue, ColonLoc);
1519 if (BeginRef.isInvalid())
1520 return StmtError();
1521
Richard Smithad762fc2011-04-14 22:09:26 +00001522 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1523 if (DerefExpr.isInvalid()) {
1524 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1525 return StmtError();
1526 }
1527
1528 // Attach *__begin as initializer for VD.
1529 if (!LoopVar->isInvalidDecl()) {
1530 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1531 /*TypeMayContainAuto=*/true);
1532 if (LoopVar->isInvalidDecl())
1533 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1534 }
Richard Smithcd6f3662011-06-21 23:07:19 +00001535 } else {
1536 // The range is implicitly used as a placeholder when it is dependent.
1537 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00001538 }
1539
1540 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1541 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1542 NotEqExpr.take(), IncrExpr.take(),
1543 LoopVarDS, /*Body=*/0, ForLoc,
1544 ColonLoc, RParenLoc));
1545}
1546
1547/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1548/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1549/// body cannot be performed until after the type of the range variable is
1550/// determined.
1551StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1552 if (!S || !B)
1553 return StmtError();
1554
1555 cast<CXXForRangeStmt>(S)->setBody(B);
1556 return S;
1557}
1558
Chris Lattner57ad3782011-02-17 20:34:02 +00001559StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1560 SourceLocation LabelLoc,
1561 LabelDecl *TheDecl) {
1562 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00001563 TheDecl->setUsed();
1564 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001565}
1566
John McCall60d7b3a2010-08-24 06:29:42 +00001567StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00001568Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001569 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00001570 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001571 if (!E->isTypeDependent()) {
1572 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00001573 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00001574 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001575 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00001576 CheckSingleAssignmentConstraints(DestTy, ExprRes);
1577 if (ExprRes.isInvalid())
1578 return StmtError();
1579 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00001580 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001581 return StmtError();
1582 }
John McCallb60a77e2010-08-01 00:26:45 +00001583
John McCall781472f2010-08-25 08:40:02 +00001584 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00001585
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00001586 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001587}
1588
John McCall60d7b3a2010-08-24 06:29:42 +00001589StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001590Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 Scope *S = CurScope->getContinueParent();
1592 if (!S) {
1593 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001594 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001596
Ted Kremenek8189cde2009-02-07 01:47:29 +00001597 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001598}
1599
John McCall60d7b3a2010-08-24 06:29:42 +00001600StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00001601Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Scope *S = CurScope->getBreakParent();
1603 if (!S) {
1604 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001605 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001607
Ted Kremenek8189cde2009-02-07 01:47:29 +00001608 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001609}
1610
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001611/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001612/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00001613///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001614/// \param ReturnType If we're determining the copy elision candidate for
1615/// a return statement, this is the return type of the function. If we're
1616/// determining the copy elision candidate for a throw expression, this will
1617/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00001618///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001619/// \param E The expression being returned from the function or block, or
1620/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00001621///
Douglas Gregor4926d832011-05-20 15:00:53 +00001622/// \param AllowFunctionParameter Whether we allow function parameters to
1623/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1624/// we re-use this logic to determine whether we should try to move as part of
1625/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00001626///
1627/// \returns The NRVO candidate variable, if the return statement may use the
1628/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001629const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1630 Expr *E,
1631 bool AllowFunctionParameter) {
1632 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001633 // - in a return statement in a function with ...
1634 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001635 if (!ReturnType.isNull()) {
1636 if (!ReturnType->isRecordType())
1637 return 0;
1638 // ... the same cv-unqualified type as the function return type ...
1639 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1640 return 0;
1641 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001642
1643 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001644 // (other than a function or catch-clause parameter)) ...
1645 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001646 if (!DR)
Douglas Gregor5077c382010-05-15 06:01:05 +00001647 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001648 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1649 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00001650 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001652 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
Douglas Gregord86c4772010-05-15 06:46:45 +00001653 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001654 !VD->getType().isVolatileQualified() &&
Douglas Gregor4a46c772011-01-21 18:20:49 +00001655 ((VD->getKind() == Decl::Var) ||
1656 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
Douglas Gregor5077c382010-05-15 06:01:05 +00001657 return VD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658
Douglas Gregor5077c382010-05-15 06:01:05 +00001659 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00001660}
1661
Douglas Gregor07f402c2011-01-21 21:08:57 +00001662/// \brief Perform the initialization of a potentially-movable value, which
1663/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00001664///
1665/// This routine implements C++0x [class.copy]p33, which attempts to treat
1666/// returned lvalues as rvalues in certain cases (to prefer move construction),
1667/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001668ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00001669Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1670 const VarDecl *NRVOCandidate,
1671 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00001672 Expr *Value,
1673 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00001674 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001675 // When the criteria for elision of a copy operation are met or would
1676 // be met save for the fact that the source object is a function
1677 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00001678 // overload resolution to select the constructor for the copy is first
1679 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00001680 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00001681 if (AllowNRVO &&
1682 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001684 Value->getType(), CK_LValueToRValue,
1685 Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001686
Douglas Gregorcc15f012011-01-21 19:38:21 +00001687 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001688 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00001689 = InitializationKind::CreateCopy(Value->getLocStart(),
1690 Value->getLocStart());
1691 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001692
1693 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00001694 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001695 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00001696 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00001697 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00001698 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1699 StepEnd = Seq.step_end();
1700 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00001701 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00001702 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001703
1704 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00001705 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001706
Douglas Gregorcc15f012011-01-21 19:38:21 +00001707 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00001708 = Constructor->getParamDecl(0)->getType()
1709 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001710
Douglas Gregorcc15f012011-01-21 19:38:21 +00001711 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001712 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00001713 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1714 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00001715 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001716
Douglas Gregorcc15f012011-01-21 19:38:21 +00001717 // Promote "AsRvalue" to the heap, since we now need this
1718 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00001719 Value = ImplicitCastExpr::Create(Context, Value->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001720 CK_LValueToRValue, Value, 0,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001721 VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722
Douglas Gregorcc15f012011-01-21 19:38:21 +00001723 // Complete type-checking the initialization of the return type
1724 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00001725 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00001726 }
1727 }
1728 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001729
Douglas Gregorcc15f012011-01-21 19:38:21 +00001730 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001731 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00001732 // (again) now with the return value expression as written.
1733 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00001734 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735
Douglas Gregorcc15f012011-01-21 19:38:21 +00001736 return Res;
1737}
1738
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001739/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001740///
John McCall60d7b3a2010-08-24 06:29:42 +00001741StmtResult
Steve Naroff4eb206b2008-09-03 18:15:37 +00001742Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00001743 // If this is the first return we've seen in the block, infer the type of
1744 // the block from it.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001745 BlockScopeInfo *CurBlock = getCurBlock();
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001746 if (CurBlock->ReturnType.isNull()) {
Steve Naroffc50a4a52008-09-16 22:25:10 +00001747 if (RetValExp) {
Steve Naroff16564422008-09-24 22:26:48 +00001748 // Don't call UsualUnaryConversions(), since we don't want to do
1749 // integer promotions here.
John Wiegley429bb272011-04-08 18:41:53 +00001750 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1751 if (Result.isInvalid())
1752 return StmtError();
1753 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00001754
1755 if (!RetValExp->isTypeDependent()) {
1756 CurBlock->ReturnType = RetValExp->getType();
1757 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1758 // We have to remove a 'const' added to copied-in variable which was
1759 // part of the implementation spec. and not the actual qualifier for
1760 // the variable.
1761 if (CDRE->isConstQualAdded())
1762 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1763 }
1764 } else
1765 CurBlock->ReturnType = Context.DependentTy;
Steve Naroffc50a4a52008-09-16 22:25:10 +00001766 } else
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001767 CurBlock->ReturnType = Context.VoidTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00001768 }
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001769 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001770
John McCall711c52b2011-01-05 12:14:39 +00001771 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
Mike Stump6c92fa72009-04-29 21:40:37 +00001772 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1773 << getCurFunctionOrMethodDecl()->getDeclName();
1774 return StmtError();
1775 }
1776
Steve Naroff4eb206b2008-09-03 18:15:37 +00001777 // Otherwise, verify that this result type matches the previous one. We are
1778 // pickier with blocks than for normal functions because we don't have GCC
1779 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00001780 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00001781 if (FnRetType->isDependentType()) {
1782 // Delay processing for now. TODO: there are lots of dependent
1783 // types we can conclusively prove aren't void.
1784 } else if (FnRetType->isVoidType()) {
1785 if (RetValExp &&
1786 !(getLangOptions().CPlusPlus &&
1787 (RetValExp->isTypeDependent() ||
1788 RetValExp->getType()->isVoidType()))) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00001789 Diag(ReturnLoc, diag::err_return_block_has_expr);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001790 RetValExp = 0;
1791 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001792 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00001793 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1794 } else if (!RetValExp->isTypeDependent()) {
1795 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001796
John McCall0a7efe12011-08-17 22:09:46 +00001797 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1798 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1799 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001800
John McCall0a7efe12011-08-17 22:09:46 +00001801 // In C++ the return statement is handled via a copy initialization.
1802 // the C version of which boils down to CheckSingleAssignmentConstraints.
1803 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1804 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1805 FnRetType,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001806 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00001807 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1808 FnRetType, RetValExp);
1809 if (Res.isInvalid()) {
1810 // FIXME: Cleanup temporaries here, anyway?
1811 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00001812 }
John McCall0a7efe12011-08-17 22:09:46 +00001813 RetValExp = Res.take();
1814 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001815 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001816
John McCalld963c372011-08-17 21:34:14 +00001817 if (RetValExp) {
1818 CheckImplicitConversions(RetValExp, ReturnLoc);
1819 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1820 }
John McCall0a7efe12011-08-17 22:09:46 +00001821 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
1822 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00001823
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001824 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00001825 // return statement in our scope for later processing.
Douglas Gregor6a576ab2011-06-05 05:04:23 +00001826 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00001827 !CurContext->isDependentContext())
1828 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001829
Douglas Gregor5077c382010-05-15 06:01:05 +00001830 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00001831}
Reid Spencer5f016e22007-07-11 17:01:13 +00001832
John McCall60d7b3a2010-08-24 06:29:42 +00001833StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001834Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00001835 // Check for unexpanded parameter packs.
1836 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1837 return StmtError();
1838
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001839 if (getCurBlock())
Steve Naroff4eb206b2008-09-03 18:15:37 +00001840 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001841
Chris Lattner371f2582008-12-04 23:50:19 +00001842 QualType FnRetType;
Douglas Gregor926df6c2011-06-11 01:09:30 +00001843 QualType DeclaredRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00001844 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00001845 FnRetType = FD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001846 DeclaredRetType = FnRetType;
John McCall04a67a62010-02-05 21:31:56 +00001847 if (FD->hasAttr<NoReturnAttr>() ||
1848 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00001849 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpf7c41da2009-04-29 00:43:21 +00001850 << getCurFunctionOrMethodDecl()->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001851 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1852 DeclaredRetType = MD->getResultType();
1853 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1854 // In the implementation of a method with a related return type, the
1855 // type used to type-check the validity of return statements within the
1856 // method body is a pointer to the type of the class being implemented.
1857 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface());
1858 FnRetType = Context.getObjCObjectPointerType(FnRetType);
1859 } else {
1860 FnRetType = DeclaredRetType;
1861 }
1862 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00001863 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor5077c382010-05-15 06:01:05 +00001865 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00001866 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00001867 if (RetValExp) {
1868 if (!RetValExp->isTypeDependent()) {
1869 // C99 6.8.6.4p1 (ext_ since GCC warns)
1870 unsigned D = diag::ext_return_has_expr;
1871 if (RetValExp->getType()->isVoidType())
1872 D = diag::ext_return_has_void_expr;
1873 else {
1874 ExprResult Result = Owned(RetValExp);
1875 Result = IgnoredValueConversions(Result.take());
1876 if (Result.isInvalid())
1877 return StmtError();
1878 RetValExp = Result.take();
1879 RetValExp = ImpCastExprToType(RetValExp,
1880 Context.VoidTy, CK_ToVoid).take();
1881 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001882
Nick Lewycky8d794612011-06-01 07:44:31 +00001883 // return (some void expression); is legal in C++.
1884 if (D != diag::ext_return_has_void_expr ||
1885 !getLangOptions().CPlusPlus) {
1886 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00001887
1888 int FunctionKind = 0;
1889 if (isa<ObjCMethodDecl>(CurDecl))
1890 FunctionKind = 1;
1891 else if (isa<CXXConstructorDecl>(CurDecl))
1892 FunctionKind = 2;
1893 else if (isa<CXXDestructorDecl>(CurDecl))
1894 FunctionKind = 3;
1895
Nick Lewycky8d794612011-06-01 07:44:31 +00001896 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00001897 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00001898 << RetValExp->getSourceRange();
1899 }
Chris Lattnere878eb02008-12-18 02:03:48 +00001900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
John McCallb4eb64d2010-10-08 02:01:28 +00001902 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00001903 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001905
Douglas Gregor5077c382010-05-15 06:01:05 +00001906 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1907 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001908 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1909 // C99 6.8.6.4p1 (ext_ since GCC warns)
1910 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1911
1912 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00001913 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00001914 else
Chris Lattner08631c52008-11-23 21:45:46 +00001915 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00001916 Result = new (Context) ReturnStmt(ReturnLoc);
1917 } else {
1918 const VarDecl *NRVOCandidate = 0;
1919 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1920 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001921
Douglas Gregor5077c382010-05-15 06:01:05 +00001922 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1923 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1924 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001925
John McCall856d3792011-06-16 23:24:51 +00001926 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00001927 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00001928 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001929 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001930 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00001931 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001932 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00001933 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00001934 if (Res.isInvalid()) {
1935 // FIXME: Cleanup temporaries here, anyway?
1936 return StmtError();
1937 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00001938
Douglas Gregor5077c382010-05-15 06:01:05 +00001939 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001940 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00001941 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001942 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001943
John McCallb4eb64d2010-10-08 02:01:28 +00001944 if (RetValExp) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001945 // If we type-checked an Objective-C method's return type based
1946 // on a related return type, we may need to adjust the return
1947 // type again. Do so now.
1948 if (DeclaredRetType != FnRetType) {
1949 ExprResult result = PerformImplicitConversion(RetValExp,
1950 DeclaredRetType,
1951 AA_Returning);
1952 if (result.isInvalid()) return StmtError();
1953 RetValExp = result.take();
1954 }
1955
John McCallb4eb64d2010-10-08 02:01:28 +00001956 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00001957 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00001958 }
Douglas Gregor5077c382010-05-15 06:01:05 +00001959 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00001960 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001961
1962 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00001963 // return statement in our scope for later processing.
1964 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1965 !CurContext->isDependentContext())
1966 FunctionScopes.back()->Returns.push_back(Result);
John McCallf85e1932011-06-15 23:02:42 +00001967
Douglas Gregor5077c382010-05-15 06:01:05 +00001968 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001969}
1970
Chris Lattner810f6d52009-03-13 17:38:01 +00001971/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1972/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1973/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1974/// provide a strong guidance to not use it.
1975///
1976/// This method checks to see if the argument is an acceptable l-value and
1977/// returns false if it is a case we can handle.
1978static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00001979 // Type dependent expressions will be checked during instantiation.
1980 if (E->isTypeDependent())
1981 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001982
John McCall7eb0a9e2010-11-24 05:12:34 +00001983 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00001984 return false; // Cool, this is an lvalue.
1985
1986 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1987 // are supposed to allow.
1988 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00001989 if (E != E2 && E2->isLValue()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00001990 if (!S.getLangOptions().HeinousExtensions)
1991 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1992 << E->getSourceRange();
1993 else
1994 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1995 << E->getSourceRange();
1996 // Accept, even if we emitted an error diagnostic.
1997 return false;
1998 }
1999
2000 // None of the above, just randomly invalid non-lvalue.
2001 return true;
2002}
2003
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002004/// isOperandMentioned - Return true if the specified operand # is mentioned
2005/// anywhere in the decomposed asm string.
2006static bool isOperandMentioned(unsigned OpNo,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002007 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002008 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2009 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2010 if (!Piece.isOperand()) continue;
2011
2012 // If this is a reference to the input and if the input was the smaller
2013 // one, then we have to reject this asm.
2014 if (Piece.getOperandNo() == OpNo)
2015 return true;
2016 }
2017
2018 return false;
2019}
Chris Lattner810f6d52009-03-13 17:38:01 +00002020
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002021StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2022 bool IsVolatile, unsigned NumOutputs,
2023 unsigned NumInputs, IdentifierInfo **Names,
2024 MultiExprArg constraints, MultiExprArg exprs,
2025 Expr *asmString, MultiExprArg clobbers,
2026 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002027 unsigned NumClobbers = clobbers.size();
2028 StringLiteral **Constraints =
2029 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00002030 Expr **Exprs = exprs.get();
2031 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00002032 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2033
Chris Lattner5f9e2722011-07-23 10:55:15 +00002034 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Chris Lattner1708b962008-08-18 19:55:17 +00002036 // The parser verifies that there is a string literal here.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002037 if (!AsmString->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002038 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2039 << AsmString->getSourceRange());
2040
Chris Lattner1708b962008-08-18 19:55:17 +00002041 for (unsigned i = 0; i != NumOutputs; i++) {
2042 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002043 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002044 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2045 << Literal->getSourceRange());
2046
Chris Lattner5f9e2722011-07-23 10:55:15 +00002047 StringRef OutputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002048 if (Names[i])
2049 OutputName = Names[i]->getName();
2050
2051 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002052 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002053 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002054 diag::err_asm_invalid_output_constraint)
2055 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00002056
Anders Carlssond04c6e22007-11-27 04:11:28 +00002057 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00002058 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00002059 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00002060 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002061 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00002062 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Chris Lattner44def072009-04-26 07:16:29 +00002065 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002066 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002067
Chris Lattner5f9e2722011-07-23 10:55:15 +00002068 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner806503f2009-05-03 05:55:43 +00002069
Anders Carlsson04728b72007-11-23 19:43:50 +00002070 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00002071 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002072 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002073 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2074 << Literal->getSourceRange());
2075
Chris Lattner5f9e2722011-07-23 10:55:15 +00002076 StringRef InputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002077 if (Names[i])
2078 InputName = Names[i]->getName();
2079
2080 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002081 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00002082 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002083 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002084 diag::err_asm_invalid_input_constraint)
2085 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00002086 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002087
Eli Friedman72056a22009-05-03 07:49:42 +00002088 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00002089
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002090 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00002091 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00002092 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00002093 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002094 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00002095 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002096 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002097 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002098
Chris Lattner44def072009-04-26 07:16:29 +00002099 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002100 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00002101 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002102 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00002103 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002104 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002105 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
John Wiegley429bb272011-04-08 18:41:53 +00002108 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2109 if (Result.isInvalid())
2110 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002111
John Wiegley429bb272011-04-08 18:41:53 +00002112 Exprs[i] = Result.take();
Chris Lattner806503f2009-05-03 05:55:43 +00002113 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002114 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002115
Anders Carlsson6fa90862007-11-25 00:25:21 +00002116 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00002117 for (unsigned i = 0; i != NumClobbers; i++) {
2118 StringLiteral *Literal = Clobbers[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002119 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002120 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2121 << Literal->getSourceRange());
2122
Chris Lattner5f9e2722011-07-23 10:55:15 +00002123 StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00002124
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002125 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002126 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00002127 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00002128 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002129
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002130 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002131 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2132 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00002133 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002134 // Validate the asm string, ensuring it makes sense given the operands we
2135 // have.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002136 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002137 unsigned DiagOffs;
2138 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00002139 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2140 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002141 return StmtError();
2142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Chris Lattner806503f2009-05-03 05:55:43 +00002144 // Validate tied input operands for type mismatches.
2145 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2146 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Chris Lattner806503f2009-05-03 05:55:43 +00002148 // If this is a tied constraint, verify that the output and input have
2149 // either exactly the same type, or that they are int/ptr operands with the
2150 // same size (int/long, int*/long, are ok etc).
2151 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Chris Lattner806503f2009-05-03 05:55:43 +00002153 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner935f0f02011-02-21 22:09:29 +00002154 unsigned InputOpNo = i+NumOutputs;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00002155 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner935f0f02011-02-21 22:09:29 +00002156 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedmanf45b3572011-09-14 19:20:00 +00002157
2158 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2159 continue;
2160
Chris Lattner7adaa182009-05-03 05:59:17 +00002161 QualType InTy = InputExpr->getType();
2162 QualType OutTy = OutputExpr->getType();
2163 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00002164 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Chris Lattneraab64d02010-04-23 17:27:29 +00002166 // Decide if the input and output are in the same domain (integer/ptr or
2167 // floating point.
2168 enum AsmDomain {
2169 AD_Int, AD_FP, AD_Other
2170 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171
Chris Lattneraab64d02010-04-23 17:27:29 +00002172 if (InTy->isIntegerType() || InTy->isPointerType())
2173 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002174 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002175 InputDomain = AD_FP;
2176 else
2177 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Chris Lattneraab64d02010-04-23 17:27:29 +00002179 if (OutTy->isIntegerType() || OutTy->isPointerType())
2180 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002181 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002182 OutputDomain = AD_FP;
2183 else
2184 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185
Chris Lattneraab64d02010-04-23 17:27:29 +00002186 // They are ok if they are the same size and in the same domain. This
2187 // allows tying things like:
2188 // void* to int*
2189 // void* to int if they are the same size.
2190 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002191 //
Chris Lattneraab64d02010-04-23 17:27:29 +00002192 uint64_t OutSize = Context.getTypeSize(OutTy);
2193 uint64_t InSize = Context.getTypeSize(InTy);
2194 if (OutSize == InSize && InputDomain == OutputDomain &&
2195 InputDomain != AD_Other)
2196 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197
Chris Lattneraab64d02010-04-23 17:27:29 +00002198 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002199 // then we can promote the smaller one to a larger input and the asm string
2200 // won't notice.
Chris Lattneraab64d02010-04-23 17:27:29 +00002201 bool SmallerValueMentioned = false;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002202
2203 // If this is a reference to the input and if the input was the smaller
2204 // one, then we have to reject this asm.
Chris Lattner935f0f02011-02-21 22:09:29 +00002205 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002206 // This is a use in the asm string of the smaller operand. Since we
2207 // codegen this by promoting to a wider value, the asm will get printed
2208 // "wrong".
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002209 SmallerValueMentioned |= InSize < OutSize;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002210 }
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002211 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002212 // If this is a reference to the output, and if the output is the larger
2213 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002214 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner806503f2009-05-03 05:55:43 +00002215 }
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Chris Lattneraab64d02010-04-23 17:27:29 +00002217 // If the smaller value wasn't mentioned in the asm string, and if the
2218 // output was a register, just extend the shorter one to the size of the
2219 // larger one.
2220 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2221 OutputConstraintInfos[TiedTo].allowsRegister())
2222 continue;
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002223
Chris Lattner935f0f02011-02-21 22:09:29 +00002224 // Either both of the operands were mentioned or the smaller one was
2225 // mentioned. One more special case that we'll allow: if the tied input is
2226 // integer, unmentioned, and is a constant, then we'll allow truncating it
2227 // down to the size of the destination.
2228 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2229 !isOperandMentioned(InputOpNo, Pieces) &&
2230 InputExpr->isEvaluatable(Context)) {
John McCall4da89c82011-05-10 23:39:47 +00002231 CastKind castKind =
2232 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2233 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner935f0f02011-02-21 22:09:29 +00002234 Exprs[InputOpNo] = InputExpr;
2235 NS->setInputExpr(i, InputExpr);
2236 continue;
2237 }
2238
Chris Lattnerc1f3b282009-05-03 06:50:40 +00002239 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00002240 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00002241 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00002242 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00002243 return StmtError();
2244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002246 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00002247}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002248
John McCall60d7b3a2010-08-24 06:29:42 +00002249StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002250Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002251 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002252 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002253 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002254 if (Var && Var->isInvalidDecl())
2255 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002256
John McCall9ae2f072010-08-23 23:25:46 +00002257 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002258}
2259
John McCall60d7b3a2010-08-24 06:29:42 +00002260StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002261Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2262 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002263}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002264
John McCall60d7b3a2010-08-24 06:29:42 +00002265StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002266Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002267 MultiStmtArg CatchStmts, Stmt *Finally) {
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002268 if (!getLangOptions().ObjCExceptions)
2269 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2270
John McCall781472f2010-08-25 08:40:02 +00002271 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002272 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002273 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2274 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002275 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002276 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002277}
2278
John McCall60d7b3a2010-08-24 06:29:42 +00002279StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002280 Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002281 if (Throw) {
Fariborz Jahanianf2dd68f2011-07-20 23:39:56 +00002282 Throw = MaybeCreateExprWithCleanups(Throw);
John Wiegley429bb272011-04-08 18:41:53 +00002283 ExprResult Result = DefaultLvalueConversion(Throw);
2284 if (Result.isInvalid())
2285 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002286
John Wiegley429bb272011-04-08 18:41:53 +00002287 Throw = Result.take();
Douglas Gregord1377b22010-04-22 21:44:01 +00002288 QualType ThrowType = Throw->getType();
2289 // Make sure the expression type is an ObjC pointer or "void *".
2290 if (!ThrowType->isDependentType() &&
2291 !ThrowType->isObjCObjectPointerType()) {
2292 const PointerType *PT = ThrowType->getAs<PointerType>();
2293 if (!PT || !PT->getPointeeType()->isVoidType())
2294 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2295 << Throw->getType() << Throw->getSourceRange());
2296 }
2297 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002298
John McCall9ae2f072010-08-23 23:25:46 +00002299 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002300}
2301
John McCall60d7b3a2010-08-24 06:29:42 +00002302StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002303Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002304 Scope *CurScope) {
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002305 if (!getLangOptions().ObjCExceptions)
2306 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2307
John McCall9ae2f072010-08-23 23:25:46 +00002308 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002309 // @throw without an expression designates a rethrow (which much occur
2310 // in the context of an @catch clause).
2311 Scope *AtCatchParent = CurScope;
2312 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2313 AtCatchParent = AtCatchParent->getParent();
2314 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002315 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002316 }
Fariborz Jahanianf2dd68f2011-07-20 23:39:56 +00002317
John McCall9ae2f072010-08-23 23:25:46 +00002318 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002319}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002320
John McCall07524032011-07-27 21:50:02 +00002321ExprResult
2322Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2323 ExprResult result = DefaultLvalueConversion(operand);
2324 if (result.isInvalid())
2325 return ExprError();
2326 operand = result.take();
2327
2328 // Make sure the expression type is an ObjC pointer or "void *".
2329 QualType type = operand->getType();
2330 if (!type->isDependentType() &&
2331 !type->isObjCObjectPointerType()) {
2332 const PointerType *pointerType = type->getAs<PointerType>();
2333 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2334 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2335 << type << operand->getSourceRange();
2336 }
2337
2338 // The operand to @synchronized is a full-expression.
2339 return MaybeCreateExprWithCleanups(operand);
2340}
2341
John McCall60d7b3a2010-08-24 06:29:42 +00002342StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002343Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2344 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002345 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002346 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002347 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002348}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002349
2350/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2351/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002352StmtResult
John McCalld226f652010-08-21 09:40:31 +00002353Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002354 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002355 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002356 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002357 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002358 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002359}
Sebastian Redl8351da02008-12-22 21:35:02 +00002360
John McCallf85e1932011-06-15 23:02:42 +00002361StmtResult
2362Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2363 getCurFunction()->setHasBranchProtectedScope();
2364 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2365}
2366
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002367namespace {
2368
Sebastian Redlc447aba2009-07-29 17:15:45 +00002369class TypeWithHandler {
2370 QualType t;
2371 CXXCatchStmt *stmt;
2372public:
2373 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2374 : t(type), stmt(statement) {}
2375
John McCall0953e762009-09-24 19:53:00 +00002376 // An arbitrary order is fine as long as it places identical
2377 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00002378 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00002379 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002380 return true;
John McCall0953e762009-09-24 19:53:00 +00002381 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00002382 return false;
2383 else
2384 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2385 }
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Sebastian Redlc447aba2009-07-29 17:15:45 +00002387 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00002388 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00002389 }
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Sebastian Redlc447aba2009-07-29 17:15:45 +00002391 CXXCatchStmt *getCatchStmt() const { return stmt; }
2392 SourceLocation getTypeSpecStartLoc() const {
2393 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2394 }
2395};
2396
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002397}
2398
Sebastian Redl8351da02008-12-22 21:35:02 +00002399/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2400/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002401StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002402Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00002403 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00002404 // Don't report an error if 'try' is used in system headers.
Anders Carlsson15348ae2011-02-28 02:27:16 +00002405 if (!getLangOptions().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00002406 !getSourceManager().isInSystemHeader(TryLoc))
2407 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00002408
Sebastian Redl8351da02008-12-22 21:35:02 +00002409 unsigned NumHandlers = RawHandlers.size();
2410 assert(NumHandlers > 0 &&
2411 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00002412 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00002413
Chris Lattner5f9e2722011-07-23 10:55:15 +00002414 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00002415
2416 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002417 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00002418 if (!Handler->getExceptionDecl()) {
2419 if (i < NumHandlers - 1)
2420 return StmtError(Diag(Handler->getLocStart(),
2421 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Sebastian Redlc447aba2009-07-29 17:15:45 +00002423 continue;
2424 }
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Sebastian Redlc447aba2009-07-29 17:15:45 +00002426 const QualType CaughtType = Handler->getCaughtType();
2427 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2428 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00002429 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00002430
2431 // Detect handlers for the same type as an earlier one.
2432 if (NumHandlers > 1) {
2433 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Sebastian Redlc447aba2009-07-29 17:15:45 +00002435 TypeWithHandler prev = TypesWithHandlers[0];
2436 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2437 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Sebastian Redlc447aba2009-07-29 17:15:45 +00002439 if (curr == prev) {
2440 Diag(curr.getTypeSpecStartLoc(),
2441 diag::warn_exception_caught_by_earlier_handler)
2442 << curr.getCatchStmt()->getCaughtType().getAsString();
2443 Diag(prev.getTypeSpecStartLoc(),
2444 diag::note_previous_exception_handler)
2445 << prev.getCatchStmt()->getCaughtType().getAsString();
2446 }
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Sebastian Redlc447aba2009-07-29 17:15:45 +00002448 prev = curr;
2449 }
2450 }
Mike Stump1eb44332009-09-09 15:08:12 +00002451
John McCall781472f2010-08-25 08:40:02 +00002452 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00002453
Sebastian Redl8351da02008-12-22 21:35:02 +00002454 // FIXME: We should detect handlers that cannot catch anything because an
2455 // earlier handler catches a superclass. Need to find a method that is not
2456 // quadratic for this.
2457 // Neither of these are explicitly forbidden, but every compiler detects them
2458 // and warns.
2459
John McCall9ae2f072010-08-23 23:25:46 +00002460 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00002461 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00002462}
John Wiegley28bbe4b2011-04-28 01:08:34 +00002463
2464StmtResult
2465Sema::ActOnSEHTryBlock(bool IsCXXTry,
2466 SourceLocation TryLoc,
2467 Stmt *TryBlock,
2468 Stmt *Handler) {
2469 assert(TryBlock && Handler);
2470
2471 getCurFunction()->setHasBranchProtectedScope();
2472
2473 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2474}
2475
2476StmtResult
2477Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2478 Expr *FilterExpr,
2479 Stmt *Block) {
2480 assert(FilterExpr && Block);
2481
2482 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00002483 return StmtError(Diag(FilterExpr->getExprLoc(),
2484 diag::err_filter_expression_integral)
2485 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00002486 }
2487
2488 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2489}
2490
2491StmtResult
2492Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2493 Stmt *Block) {
2494 assert(Block);
2495 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2496}
Douglas Gregorba0513d2011-10-25 01:33:02 +00002497
2498StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2499 bool IsIfExists,
2500 NestedNameSpecifierLoc QualifierLoc,
2501 DeclarationNameInfo NameInfo,
2502 Stmt *Nested)
2503{
2504 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2505 QualifierLoc, NameInfo,
2506 cast<CompoundStmt>(Nested));
2507}
2508
2509
2510StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2511 bool IsIfExists,
2512 CXXScopeSpec &SS,
2513 UnqualifiedId &Name,
2514 Stmt *Nested) {
2515 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2516 SS.getWithLocInContext(Context),
2517 GetNameFromUnqualifiedId(Name),
2518 Nested);
2519}