blob: a8a06a93fcfbaad7e8d57a51701d2954e8d234c4 [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"
Chris Lattnerf4021e72007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall1cd76e82011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu694e7962012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall209acbd2010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor84fb9c02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattnerca57b4b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000031#include "llvm/ADT/STLExtras.h"
Richard Trieu694e7962012-04-30 18:01:30 +000032#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor50de5e32012-05-16 16:11:17 +000033#include "llvm/ADT/SmallString.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000034#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000036using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000037
John McCall60d7b3a2010-08-24 06:29:42 +000038StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000039 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000040 if (!E) // FIXME: FullExprArg has no error state?
41 return StmtError();
42
Chris Lattner834a72a2008-07-25 23:18:17 +000043 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
44 // void expression for its side effects. Conversion to void allows any
45 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000046
Chris Lattner834a72a2008-07-25 23:18:17 +000047 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000048 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000049}
50
51
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000052StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000053 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Chris Lattner337e5502011-02-18 01:27:55 +000057StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000059 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner20401692009-04-12 20:13:14 +000061 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner24e1e702009-03-04 04:23:07 +000064 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000065}
66
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000067void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000069
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000070 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000072 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000074 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000075 var->setUsed();
76
John McCall7acddac2011-06-17 06:42:21 +000077 // foreach variables are never actually initialized in the way that
78 // the parser came up with.
79 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000080
John McCall7acddac2011-06-17 06:42:21 +000081 // In ARC, we don't need to retain the iteration variable of a fast
82 // enumeration loop. Rather than actually trying to catch that
83 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000084 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000085 QualType type = var->getType();
86
87 // Only do this if we inferred the lifetime. Inferred lifetime
88 // will show up as a local qualifier because explicit lifetime
89 // should have shown up as an AttributedType instead.
90 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
91 // Add 'const' and mark the variable as pseudo-strong.
92 var->setType(type.withConst());
93 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000094 }
95 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000096}
97
Chandler Carruthec8058f2011-08-17 09:34:37 +000098/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +000099///
100/// Adding a cast to void (or other expression wrappers) will prevent the
101/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000102static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000103 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000104 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000105
106 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
107 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000108 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000109
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000113 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
114 if (Op->getOperator() != OO_EqualEqual &&
115 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000116 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000117
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000121 } else {
122 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000123 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000124 }
125
126 // Suppress warnings when the operator, suspicious as it may be, comes from
127 // a macro expansion.
128 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000129 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000130
Chandler Carruthec8058f2011-08-17 09:34:37 +0000131 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000132 << (unsigned)IsNotEqual << E->getSourceRange();
133
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000134 // If the LHS is a plausible entity to assign to, provide a fixit hint to
135 // correct common typos.
136 if (CanAssign) {
137 if (IsNotEqual)
138 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
139 << FixItHint::CreateReplacement(Loc, "|=");
140 else
141 S.Diag(Loc, diag::note_equality_comparison_to_assign)
142 << FixItHint::CreateReplacement(Loc, "=");
143 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000144
145 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000146}
147
Anders Carlsson636463e2009-07-30 22:17:18 +0000148void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
151
Anders Carlsson75443112009-07-30 22:39:03 +0000152 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000153 if (!E)
154 return;
155
Eli Friedmana6115062012-05-24 00:47:05 +0000156 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000157 SourceLocation Loc;
158 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000161 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner419cfb32009-08-16 16:57:27 +0000163 // Okay, we have an unused result. Depending on what the base expression is,
164 // we might want to make a more specific diagnostic. Check for one of these
165 // cases now.
166 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000167 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000168 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000169 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
170 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000171
Chandler Carruthec8058f2011-08-17 09:34:37 +0000172 if (DiagnoseUnusedComparison(*this, E))
173 return;
174
Eli Friedmana6115062012-05-24 00:47:05 +0000175 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000176 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000177 if (E->getType()->isVoidType())
178 return;
179
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000180 // If the callee has attribute pure, const, or warn_unused_result, warn with
181 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000182 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000183 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000184 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000185 return;
186 }
187 if (FD->getAttr<PureAttr>()) {
188 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
189 return;
190 }
191 if (FD->getAttr<ConstAttr>()) {
192 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
193 return;
194 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000195 }
John McCall12f78a62010-12-02 01:19:52 +0000196 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000197 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000198 Diag(Loc, diag::err_arc_unused_init_message) << R1;
199 return;
200 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000201 const ObjCMethodDecl *MD = ME->getMethodDecl();
202 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000203 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000204 return;
205 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000206 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
207 const Expr *Source = POE->getSyntacticForm();
208 if (isa<ObjCSubscriptRefExpr>(Source))
209 DiagID = diag::warn_unused_container_subscript_expr;
210 else
211 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000212 } else if (const CXXFunctionalCastExpr *FC
213 = dyn_cast<CXXFunctionalCastExpr>(E)) {
214 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
215 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
216 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000217 }
John McCall209acbd2010-04-06 22:24:14 +0000218 // Diagnose "(void*) blah" as a typo for "(void) blah".
219 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
220 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
221 QualType T = TI->getType();
222
223 // We really do want to use the non-canonical type here.
224 if (T == Context.VoidPtrTy) {
225 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
226
227 Diag(Loc, diag::warn_unused_voidptr)
228 << FixItHint::CreateRemoval(TL.getStarLoc());
229 return;
230 }
231 }
232
Eli Friedmana6115062012-05-24 00:47:05 +0000233 if (E->isGLValue() && E->getType().isVolatileQualified()) {
234 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
235 return;
236 }
237
Ted Kremenek351ba912011-02-23 01:52:04 +0000238 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000239}
240
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000241void Sema::ActOnStartOfCompoundStmt() {
242 PushCompoundScope();
243}
244
245void Sema::ActOnFinishOfCompoundStmt() {
246 PopCompoundScope();
247}
248
249sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
250 return getCurFunction()->CompoundScopes.back();
251}
252
John McCall60d7b3a2010-08-24 06:29:42 +0000253StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000254Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000255 MultiStmtArg elts, bool isStmtExpr) {
256 unsigned NumElts = elts.size();
257 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000258 // If we're in C89 mode, check that we don't have any decls after stmts. If
259 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000260 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000261 // Note that __extension__ can be around a decl.
262 unsigned i = 0;
263 // Skip over all declarations.
264 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
265 /*empty*/;
266
267 // We found the end of the list or a statement. Scan for another declstmt.
268 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
269 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000271 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000272 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000273 Diag(D->getLocation(), diag::ext_mixed_decls_code);
274 }
275 }
Chris Lattner98414c12007-08-31 21:49:55 +0000276 // Warn about unused expressions in statements.
277 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000278 // Ignore statements that are last in a statement expression.
279 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000280 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Anders Carlsson636463e2009-07-30 22:17:18 +0000282 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000283 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000284
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000285 // Check for suspicious empty body (null statement) in `for' and `while'
286 // statements. Don't do anything for template instantiations, this just adds
287 // noise.
288 if (NumElts != 0 && !CurrentInstantiationScope &&
289 getCurCompoundScope().HasEmptyLoopBodies) {
290 for (unsigned i = 0; i != NumElts - 1; ++i)
291 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
292 }
293
Ted Kremenek8189cde2009-02-07 01:47:29 +0000294 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000295}
296
John McCall60d7b3a2010-08-24 06:29:42 +0000297StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000298Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
299 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000300 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000301 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000302
John McCall781472f2010-08-25 08:40:02 +0000303 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000304 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000305 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000306 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000307
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000309 // C99 6.8.4.2p3: The expression shall be an integer constant.
310 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000311 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
312 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
313 if (!LHSVal)
314 return StmtError();
315 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000316
317 // GCC extension: The expression shall be an integer constant.
318
Richard Smith282e7e62012-02-04 09:53:13 +0000319 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
320 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
321 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000322 }
323 }
324
Douglas Gregordbb26db2009-05-15 23:57:33 +0000325 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
326 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000327 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000328 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000329}
330
Chris Lattner24e1e702009-03-04 04:23:07 +0000331/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000332void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000333 DiagnoseUnusedExprResult(SubStmt);
334
Chris Lattner24e1e702009-03-04 04:23:07 +0000335 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000336 CS->setSubStmt(SubStmt);
337}
338
John McCall60d7b3a2010-08-24 06:29:42 +0000339StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000340Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000341 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000342 DiagnoseUnusedExprResult(SubStmt);
343
John McCall781472f2010-08-25 08:40:02 +0000344 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000345 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000346 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000347 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000348
Douglas Gregordbb26db2009-05-15 23:57:33 +0000349 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000350 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000351 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
John McCall60d7b3a2010-08-24 06:29:42 +0000354StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000355Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
356 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000357 // If the label was multiply defined, reject it now.
358 if (TheDecl->getStmt()) {
359 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
360 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000361 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 }
Sebastian Redlde307472009-01-11 00:38:46 +0000363
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000364 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000365 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
366 TheDecl->setStmt(LS);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000367 if (!TheDecl->isGnuLocal())
368 TheDecl->setLocation(IdentLoc);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000369 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
Richard Smith534986f2012-04-14 00:33:13 +0000372StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000373 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000374 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000375 // Fill in the declaration and return it.
376 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000377 return Owned(LS);
378}
379
John McCall60d7b3a2010-08-24 06:29:42 +0000380StmtResult
John McCalld226f652010-08-21 09:40:31 +0000381Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000382 Stmt *thenStmt, SourceLocation ElseLoc,
383 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000384 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000386 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000387 if (CondVar) {
388 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000389 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000390 if (CondResult.isInvalid())
391 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000392 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000393 Expr *ConditionExpr = CondResult.takeAs<Expr>();
394 if (!ConditionExpr)
395 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396
Anders Carlsson75443112009-07-30 22:39:03 +0000397 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398
John McCall9ae2f072010-08-23 23:25:46 +0000399 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000400 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
401 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000402 }
403
Anders Carlsson75443112009-07-30 22:39:03 +0000404 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000405
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000407 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000408}
409
Chris Lattnerf4021e72007-08-23 05:46:52 +0000410/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
411/// the specified width and sign. If an overflow occurs, detect it and emit
412/// the specified diagnostic.
413void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
414 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000415 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000416 unsigned DiagID) {
417 // Perform a conversion to the promoted condition type if needed.
418 if (NewWidth > Val.getBitWidth()) {
419 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000420 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000421 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000422
423 // If the input was signed and negative and the output is
424 // unsigned, don't bother to warn: this is implementation-defined
425 // behavior.
426 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000427 } else if (NewWidth < Val.getBitWidth()) {
428 // If this is a truncation, check for overflow.
429 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000430 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000431 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000432 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000433 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000434 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000435 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattnerf4021e72007-08-23 05:46:52 +0000437 // Regardless of whether a diagnostic was emitted, really do the
438 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000439 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000440 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000441 } else if (NewSign != Val.isSigned()) {
442 // Convert the sign to match the sign of the condition. This can cause
443 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000445 // behavior.
446 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000447 llvm::APSInt OldVal(Val);
448 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000449 }
450}
451
Chris Lattner0471f5b2007-08-23 18:29:20 +0000452namespace {
453 struct CaseCompareFunctor {
454 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
455 const llvm::APSInt &RHS) {
456 return LHS.first < RHS;
457 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000458 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
459 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
460 return LHS.first < RHS.first;
461 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000462 bool operator()(const llvm::APSInt &LHS,
463 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
464 return LHS < RHS.first;
465 }
466 };
467}
468
Chris Lattner764a7ce2007-09-21 18:15:22 +0000469/// CmpCaseVals - Comparison predicate for sorting case values.
470///
471static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
472 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
473 if (lhs.first < rhs.first)
474 return true;
475
476 if (lhs.first == rhs.first &&
477 lhs.second->getCaseLoc().getRawEncoding()
478 < rhs.second->getCaseLoc().getRawEncoding())
479 return true;
480 return false;
481}
482
Douglas Gregorba915af2010-02-08 22:24:16 +0000483/// CmpEnumVals - Comparison predicate for sorting enumeration values.
484///
485static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
486 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
487{
488 return lhs.first < rhs.first;
489}
490
491/// EqEnumVals - Comparison preficate for uniqing enumeration values.
492///
493static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
494 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
495{
496 return lhs.first == rhs.first;
497}
498
Chris Lattner5f048812009-10-16 16:45:22 +0000499/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
500/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000501static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
502 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
503 expr = cleanups->getSubExpr();
504 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
505 if (impcast->getCastKind() != CK_IntegralCast) break;
506 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000507 }
508 return expr->getType();
509}
510
John McCall60d7b3a2010-08-24 06:29:42 +0000511StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000512Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000513 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000514 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000515
Douglas Gregor586596f2010-05-06 17:25:47 +0000516 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000517 if (CondVar) {
518 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000519 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
520 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000521 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000522
John McCall9ae2f072010-08-23 23:25:46 +0000523 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000525
John McCall9ae2f072010-08-23 23:25:46 +0000526 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000527 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000528
Douglas Gregorab41fe92012-05-04 22:38:52 +0000529 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
530 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000531
Douglas Gregorab41fe92012-05-04 22:38:52 +0000532 public:
533 SwitchConvertDiagnoser(Expr *Cond)
534 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000535
Douglas Gregorab41fe92012-05-04 22:38:52 +0000536 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
537 QualType T) {
538 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
539 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000540
Douglas Gregorab41fe92012-05-04 22:38:52 +0000541 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
542 QualType T) {
543 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
544 << T << Cond->getSourceRange();
545 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000546
Douglas Gregorab41fe92012-05-04 22:38:52 +0000547 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
548 QualType T,
549 QualType ConvTy) {
550 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
551 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000552
Douglas Gregorab41fe92012-05-04 22:38:52 +0000553 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
554 QualType ConvTy) {
555 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
556 << ConvTy->isEnumeralType() << ConvTy;
557 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000558
Douglas Gregorab41fe92012-05-04 22:38:52 +0000559 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
560 QualType T) {
561 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
562 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000563
Douglas Gregorab41fe92012-05-04 22:38:52 +0000564 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
565 QualType ConvTy) {
566 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
567 << ConvTy->isEnumeralType() << ConvTy;
568 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000569
Douglas Gregorab41fe92012-05-04 22:38:52 +0000570 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
571 QualType T,
572 QualType ConvTy) {
573 return DiagnosticBuilder::getEmpty();
574 }
575 } SwitchDiagnoser(Cond);
576
John McCall9ae2f072010-08-23 23:25:46 +0000577 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000578 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000579 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000580 if (CondResult.isInvalid()) return StmtError();
581 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582
John McCalla8e0cd82011-08-06 07:30:58 +0000583 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
584 CondResult = UsualUnaryConversions(Cond);
585 if (CondResult.isInvalid()) return StmtError();
586 Cond = CondResult.take();
587
John McCalld226f652010-08-21 09:40:31 +0000588 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000589 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000590 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000591 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000592 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000593 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000594 }
John McCallb60a77e2010-08-01 00:26:45 +0000595
John McCall781472f2010-08-25 08:40:02 +0000596 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000597
John McCall9ae2f072010-08-23 23:25:46 +0000598 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000599 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000600 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000601}
602
Gabor Greif28164ab2010-10-01 22:05:14 +0000603static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
604 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000605 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000606 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000607 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000608 Val.setIsSigned(IsSigned);
609}
610
John McCall60d7b3a2010-08-24 06:29:42 +0000611StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000612Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
613 Stmt *BodyStmt) {
614 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000615 assert(SS == getCurFunction()->SwitchStack.back() &&
616 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000617
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000618 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000619 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000620
Chris Lattnerf4021e72007-08-23 05:46:52 +0000621 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000622 if (!CondExpr) return StmtError();
623
624 QualType CondType = CondExpr->getType();
625
John McCall0fb97082010-05-18 03:19:21 +0000626 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000627 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000628 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000629
Chris Lattner5f048812009-10-16 16:45:22 +0000630 // C++ 6.4.2.p2:
631 // Integral promotions are performed (on the switch condition).
632 //
633 // A case value unrepresentable by the original switch condition
634 // type (before the promotion) doesn't make sense, even when it can
635 // be represented by the promoted type. Therefore we need to find
636 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000637 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000638 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000640 // appropriate type now, just return an error.
641 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000642 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000643
Chris Lattner2b334bb2010-04-16 23:34:13 +0000644 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000645 // switch(bool_expr) {...} is often a programmer error, e.g.
646 // switch(n && mask) { ... } // Doh - should be "n & mask".
647 // One can always use an if statement instead of switch(bool_expr).
648 Diag(SwitchLoc, diag::warn_bool_switch_condition)
649 << CondExpr->getSourceRange();
650 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000651 }
Sebastian Redlde307472009-01-11 00:38:46 +0000652
Chris Lattnerf4021e72007-08-23 05:46:52 +0000653 // Get the bitwidth of the switched-on value before promotions. We must
654 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000655 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000656 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000657 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000658 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000659 bool CondIsSigned
660 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattnerf4021e72007-08-23 05:46:52 +0000662 // Accumulate all of the case values in a vector so that we can sort them
663 // and detect duplicates. This vector contains the APInt for the case after
664 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000665 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000666 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Chris Lattnerf4021e72007-08-23 05:46:52 +0000668 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000669 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
670 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Chris Lattnerf4021e72007-08-23 05:46:52 +0000672 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000674 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Douglas Gregordbb26db2009-05-15 23:57:33 +0000676 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000677 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000679 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000680 if (TheDefaultStmt) {
681 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000682 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000683
Chris Lattnerf4021e72007-08-23 05:46:52 +0000684 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000685 // we'll return a valid AST. This requires recursing down the AST and
686 // finding it, not something we are set up to do right now. For now,
687 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000688 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000689 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000690 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattnerf4021e72007-08-23 05:46:52 +0000692 } else {
693 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner1e0a3902008-01-16 19:17:22 +0000695 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000696
697 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
698 HasDependentValue = true;
699 break;
700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Richard Smith8ef7b202012-01-18 23:55:52 +0000702 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
David Blaikie4e4d0842012-03-11 07:00:24 +0000704 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000705 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
706 // constant expression of the promoted type of the switch condition.
707 ExprResult ConvLo =
708 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
709 if (ConvLo.isInvalid()) {
710 CaseListIsErroneous = true;
711 continue;
712 }
713 Lo = ConvLo.take();
714 } else {
715 // We already verified that the expression has a i-c-e value (C99
716 // 6.8.4.2p3) - get that value now.
717 LoVal = Lo->EvaluateKnownConstInt(Context);
718
719 // If the LHS is not the same type as the condition, insert an implicit
720 // cast.
721 Lo = DefaultLvalueConversion(Lo).take();
722 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
723 }
724
725 // Convert the value to the same width/sign as the condition had prior to
726 // integral promotions.
727 //
728 // FIXME: This causes us to reject valid code:
729 // switch ((char)c) { case 256: case 0: return 0; }
730 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000731 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000732 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000733 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000734
Chris Lattner1e0a3902008-01-16 19:17:22 +0000735 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000737 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000738 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000739 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000740 CS->getRHS()->isValueDependent()) {
741 HasDependentValue = true;
742 break;
743 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000744 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000745 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000746 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000747 }
748 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000749
750 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000751 // If we don't have a default statement, check whether the
752 // condition is constant.
753 llvm::APSInt ConstantCondValue;
754 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000755 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000756 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000757 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
758 Expr::SE_AllowSideEffects);
759 assert(!HasConstantCond ||
760 (ConstantCondValue.getBitWidth() == CondWidth &&
761 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000762 }
Richard Smith80d4b552011-12-28 19:48:30 +0000763 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000764
Douglas Gregordbb26db2009-05-15 23:57:33 +0000765 // Sort all the scalar case values so we can easily detect duplicates.
766 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
767
768 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000769 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
770 if (ShouldCheckConstantCond &&
771 CaseVals[i].first == ConstantCondValue)
772 ShouldCheckConstantCond = false;
773
774 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000775 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000776 // First, determine if either case value has a name
777 StringRef PrevString, CurrString;
778 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
779 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
780 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
781 PrevString = DeclRef->getDecl()->getName();
782 }
783 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
784 CurrString = DeclRef->getDecl()->getName();
785 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000786 llvm::SmallString<16> CaseValStr;
787 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000788
789 if (PrevString == CurrString)
790 Diag(CaseVals[i].second->getLHS()->getLocStart(),
791 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000792 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000793 else
794 Diag(CaseVals[i].second->getLHS()->getLocStart(),
795 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000796 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
797 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000798 CaseValStr;
799
John McCall0fb97082010-05-18 03:19:21 +0000800 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000801 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000802 // FIXME: We really want to remove the bogus case stmt from the
803 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000804 CaseListIsErroneous = true;
805 }
806 }
807 }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregordbb26db2009-05-15 23:57:33 +0000809 // Detect duplicate case ranges, which usually don't exist at all in
810 // the first place.
811 if (!CaseRanges.empty()) {
812 // Sort all the case ranges by their low value so we can easily detect
813 // overlaps between ranges.
814 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Douglas Gregordbb26db2009-05-15 23:57:33 +0000816 // Scan the ranges, computing the high values and removing empty ranges.
817 std::vector<llvm::APSInt> HiVals;
818 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000819 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000820 CaseStmt *CR = CaseRanges[i].second;
821 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000822 llvm::APSInt HiVal;
823
David Blaikie4e4d0842012-03-11 07:00:24 +0000824 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000825 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
826 // constant expression of the promoted type of the switch condition.
827 ExprResult ConvHi =
828 CheckConvertedConstantExpression(Hi, CondType, HiVal,
829 CCEK_CaseValue);
830 if (ConvHi.isInvalid()) {
831 CaseListIsErroneous = true;
832 continue;
833 }
834 Hi = ConvHi.take();
835 } else {
836 HiVal = Hi->EvaluateKnownConstInt(Context);
837
838 // If the RHS is not the same type as the condition, insert an
839 // implicit cast.
840 Hi = DefaultLvalueConversion(Hi).take();
841 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
842 }
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Douglas Gregordbb26db2009-05-15 23:57:33 +0000844 // Convert the value to the same width/sign as the condition.
845 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000846 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000847 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Douglas Gregordbb26db2009-05-15 23:57:33 +0000849 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregordbb26db2009-05-15 23:57:33 +0000851 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000852 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000853 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
854 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000855 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000856 CaseRanges.erase(CaseRanges.begin()+i);
857 --i, --e;
858 continue;
859 }
John McCall0fb97082010-05-18 03:19:21 +0000860
861 if (ShouldCheckConstantCond &&
862 LoVal <= ConstantCondValue &&
863 ConstantCondValue <= HiVal)
864 ShouldCheckConstantCond = false;
865
Douglas Gregordbb26db2009-05-15 23:57:33 +0000866 HiVals.push_back(HiVal);
867 }
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Douglas Gregordbb26db2009-05-15 23:57:33 +0000869 // Rescan the ranges, looking for overlap with singleton values and other
870 // ranges. Since the range list is sorted, we only need to compare case
871 // ranges with their neighbors.
872 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
873 llvm::APSInt &CRLo = CaseRanges[i].first;
874 llvm::APSInt &CRHi = HiVals[i];
875 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Douglas Gregordbb26db2009-05-15 23:57:33 +0000877 // Check to see whether the case range overlaps with any
878 // singleton cases.
879 CaseStmt *OverlapStmt = 0;
880 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Douglas Gregordbb26db2009-05-15 23:57:33 +0000882 // Find the smallest value >= the lower bound. If I is in the
883 // case range, then we have overlap.
884 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
885 CaseVals.end(), CRLo,
886 CaseCompareFunctor());
887 if (I != CaseVals.end() && I->first < CRHi) {
888 OverlapVal = I->first; // Found overlap with scalar.
889 OverlapStmt = I->second;
890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregordbb26db2009-05-15 23:57:33 +0000892 // Find the smallest value bigger than the upper bound.
893 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
894 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
895 OverlapVal = (I-1)->first; // Found overlap with scalar.
896 OverlapStmt = (I-1)->second;
897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Douglas Gregordbb26db2009-05-15 23:57:33 +0000899 // Check to see if this case stmt overlaps with the subsequent
900 // case range.
901 if (i && CRLo <= HiVals[i-1]) {
902 OverlapVal = HiVals[i-1]; // Found overlap with range.
903 OverlapStmt = CaseRanges[i-1].second;
904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregordbb26db2009-05-15 23:57:33 +0000906 if (OverlapStmt) {
907 // If we have a duplicate, report it.
908 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
909 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000910 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000911 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000912 // FIXME: We really want to remove the bogus case stmt from the
913 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000914 CaseListIsErroneous = true;
915 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000916 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000917 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000918
John McCall0fb97082010-05-18 03:19:21 +0000919 // Complain if we have a constant condition and we didn't find a match.
920 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
921 // TODO: it would be nice if we printed enums as enums, chars as
922 // chars, etc.
923 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
924 << ConstantCondValue.toString(10)
925 << CondExpr->getSourceRange();
926 }
927
928 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000929 // values. We only issue a warning if there is not 'default:', but
930 // we still do the analysis to preserve this information in the AST
931 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000932 //
Chris Lattnerce784612010-09-16 17:09:42 +0000933 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000934
Douglas Gregorba915af2010-02-08 22:24:16 +0000935 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000936 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000937 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000938 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000939 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000940 EnumValsTy EnumVals;
941
John McCall0fb97082010-05-18 03:19:21 +0000942 // Gather all enum values, set their type and sort them,
943 // allowing easier comparison with CaseVals.
944 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000945 EDI != ED->enumerator_end(); ++EDI) {
946 llvm::APSInt Val = EDI->getInitVal();
947 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000948 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000949 }
950 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000951 EnumValsTy::iterator EIend =
952 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000953
954 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000955 EnumValsTy::const_iterator EI = EnumVals.begin();
956 for (CaseValsTy::const_iterator CI = CaseVals.begin();
957 CI != CaseVals.end(); CI++) {
958 while (EI != EIend && EI->first < CI->first)
959 EI++;
960 if (EI == EIend || EI->first > CI->first)
961 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000962 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000963 }
964 // See which of case ranges aren't in enum
965 EI = EnumVals.begin();
966 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
967 RI != CaseRanges.end() && EI != EIend; RI++) {
968 while (EI != EIend && EI->first < RI->first)
969 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000970
David Blaikie93667502012-01-22 02:31:55 +0000971 if (EI == EIend || EI->first != RI->first) {
972 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000973 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000974 }
David Blaikie93667502012-01-22 02:31:55 +0000975
976 llvm::APSInt Hi =
977 RI->second->getRHS()->EvaluateKnownConstInt(Context);
978 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
979 while (EI != EIend && EI->first < Hi)
980 EI++;
981 if (EI == EIend || EI->first != Hi)
982 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000983 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +0000984 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000985
Ted Kremenek559fb552010-09-09 00:05:53 +0000986 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000987 CaseValsTy::const_iterator CI = CaseVals.begin();
988 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000989 bool hasCasesNotInSwitch = false;
990
Chris Lattner5f9e2722011-07-23 10:55:15 +0000991 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000992
David Blaikie93667502012-01-22 02:31:55 +0000993 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000994 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000995 llvm::APSInt CIVal;
996 while (CI != CaseVals.end() && CI->first < EI->first)
997 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998
Douglas Gregorba915af2010-02-08 22:24:16 +0000999 if (CI != CaseVals.end() && CI->first == EI->first)
1000 continue;
1001
Ted Kremenek559fb552010-09-09 00:05:53 +00001002 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001003 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001004 llvm::APSInt Hi =
1005 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001006 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001007 if (EI->first <= Hi)
1008 break;
1009 }
1010
Ted Kremenek559fb552010-09-09 00:05:53 +00001011 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001012 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001013 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001014 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001015 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001016
David Blaikie585d7792012-01-23 04:46:12 +00001017 if (TheDefaultStmt && UnhandledNames.empty())
1018 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001019
Chris Lattnerce784612010-09-16 17:09:42 +00001020 // Produce a nice diagnostic if multiple values aren't handled.
1021 switch (UnhandledNames.size()) {
1022 case 0: break;
1023 case 1:
David Blaikie585d7792012-01-23 04:46:12 +00001024 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1025 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001026 << UnhandledNames[0];
1027 break;
1028 case 2:
David Blaikie585d7792012-01-23 04:46:12 +00001029 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1030 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001031 << UnhandledNames[0] << UnhandledNames[1];
1032 break;
1033 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001034 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1035 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001036 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1037 break;
1038 default:
David Blaikie585d7792012-01-23 04:46:12 +00001039 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1040 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001041 << (unsigned)UnhandledNames.size()
1042 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1043 break;
1044 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001045
1046 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001047 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001048 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001049 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001050
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001051 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1052 diag::warn_empty_switch_body);
1053
Mike Stump390b4cc2009-05-16 07:39:55 +00001054 // FIXME: If the case list was broken is some way, we don't have a good system
1055 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001056 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001057 return StmtError();
1058
Sebastian Redlde307472009-01-11 00:38:46 +00001059 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001060}
1061
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001062void
1063Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1064 Expr *SrcExpr) {
1065 unsigned DIAG = diag::warn_not_in_enum_assignement;
1066 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1067 == DiagnosticsEngine::Ignored)
1068 return;
1069
1070 if (const EnumType *ET = DstType->getAs<EnumType>())
1071 if (!Context.hasSameType(SrcType, DstType) &&
1072 SrcType->isIntegerType()) {
1073 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1074 SrcExpr->isIntegerConstantExpr(Context)) {
1075 // Get the bitwidth of the enum value before promotions.
1076 unsigned DstWith = Context.getIntWidth(DstType);
1077 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1078
1079 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1080 const EnumDecl *ED = ET->getDecl();
1081 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1082 EnumValsTy;
1083 EnumValsTy EnumVals;
1084
1085 // Gather all enum values, set their type and sort them,
1086 // allowing easier comparison with rhs constant.
1087 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1088 EDI != ED->enumerator_end(); ++EDI) {
1089 llvm::APSInt Val = EDI->getInitVal();
1090 AdjustAPSInt(Val, DstWith, DstIsSigned);
1091 EnumVals.push_back(std::make_pair(Val, *EDI));
1092 }
1093 if (EnumVals.empty())
1094 return;
1095 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1096 EnumValsTy::iterator EIend =
1097 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1098
1099 // See which case values aren't in enum.
1100 EnumValsTy::const_iterator EI = EnumVals.begin();
1101 while (EI != EIend && EI->first < RhsVal)
1102 EI++;
1103 if (EI == EIend || EI->first != RhsVal) {
1104 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1105 << DstType;
1106 }
1107 }
1108 }
1109}
1110
John McCall60d7b3a2010-08-24 06:29:42 +00001111StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001112Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001113 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001114 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001115
Douglas Gregor5656e142009-11-24 21:15:44 +00001116 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001117 if (CondVar) {
1118 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001119 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001120 if (CondResult.isInvalid())
1121 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001122 }
John McCall9ae2f072010-08-23 23:25:46 +00001123 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001124 if (!ConditionExpr)
1125 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126
John McCall9ae2f072010-08-23 23:25:46 +00001127 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001129 if (isa<NullStmt>(Body))
1130 getCurCompoundScope().setHasEmptyLoopBodies();
1131
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001132 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001133 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001134}
1135
John McCall60d7b3a2010-08-24 06:29:42 +00001136StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001137Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001138 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001139 Expr *Cond, SourceLocation CondRParen) {
1140 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001141
John Wiegley429bb272011-04-08 18:41:53 +00001142 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1143 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001144 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001145 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001146
John McCallb4eb64d2010-10-08 02:01:28 +00001147 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001148 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001149 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001150 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001151 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001152
John McCall9ae2f072010-08-23 23:25:46 +00001153 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001154
John McCall9ae2f072010-08-23 23:25:46 +00001155 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001156}
1157
Richard Trieu694e7962012-04-30 18:01:30 +00001158namespace {
1159 // This visitor will traverse a conditional statement and store all
1160 // the evaluated decls into a vector. Simple is set to true if none
1161 // of the excluded constructs are used.
1162 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1163 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1164 llvm::SmallVector<SourceRange, 10> &Ranges;
1165 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001166public:
1167 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1168
1169 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001170 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001171 Inherited(S.Context),
1172 Decls(Decls),
1173 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001174 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001175
1176 bool isSimple() { return Simple; }
1177
1178 // Replaces the method in EvaluatedExprVisitor.
1179 void VisitMemberExpr(MemberExpr* E) {
1180 Simple = false;
1181 }
1182
1183 // Any Stmt not whitelisted will cause the condition to be marked complex.
1184 void VisitStmt(Stmt *S) {
1185 Simple = false;
1186 }
1187
1188 void VisitBinaryOperator(BinaryOperator *E) {
1189 Visit(E->getLHS());
1190 Visit(E->getRHS());
1191 }
1192
1193 void VisitCastExpr(CastExpr *E) {
1194 Visit(E->getSubExpr());
1195 }
1196
1197 void VisitUnaryOperator(UnaryOperator *E) {
1198 // Skip checking conditionals with derefernces.
1199 if (E->getOpcode() == UO_Deref)
1200 Simple = false;
1201 else
1202 Visit(E->getSubExpr());
1203 }
1204
1205 void VisitConditionalOperator(ConditionalOperator *E) {
1206 Visit(E->getCond());
1207 Visit(E->getTrueExpr());
1208 Visit(E->getFalseExpr());
1209 }
1210
1211 void VisitParenExpr(ParenExpr *E) {
1212 Visit(E->getSubExpr());
1213 }
1214
1215 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1216 Visit(E->getOpaqueValue()->getSourceExpr());
1217 Visit(E->getFalseExpr());
1218 }
1219
1220 void VisitIntegerLiteral(IntegerLiteral *E) { }
1221 void VisitFloatingLiteral(FloatingLiteral *E) { }
1222 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1223 void VisitCharacterLiteral(CharacterLiteral *E) { }
1224 void VisitGNUNullExpr(GNUNullExpr *E) { }
1225 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1226
1227 void VisitDeclRefExpr(DeclRefExpr *E) {
1228 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1229 if (!VD) return;
1230
1231 Ranges.push_back(E->getSourceRange());
1232
1233 Decls.insert(VD);
1234 }
1235
1236 }; // end class DeclExtractor
1237
1238 // DeclMatcher checks to see if the decls are used in a non-evauluated
1239 // context.
1240 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1241 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1242 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001243
1244public:
1245 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1246
1247 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1248 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1249 if (!Statement) return;
1250
1251 Visit(Statement);
1252 }
1253
1254 void VisitReturnStmt(ReturnStmt *S) {
1255 FoundDecl = true;
1256 }
1257
1258 void VisitBreakStmt(BreakStmt *S) {
1259 FoundDecl = true;
1260 }
1261
1262 void VisitGotoStmt(GotoStmt *S) {
1263 FoundDecl = true;
1264 }
1265
1266 void VisitCastExpr(CastExpr *E) {
1267 if (E->getCastKind() == CK_LValueToRValue)
1268 CheckLValueToRValueCast(E->getSubExpr());
1269 else
1270 Visit(E->getSubExpr());
1271 }
1272
1273 void CheckLValueToRValueCast(Expr *E) {
1274 E = E->IgnoreParenImpCasts();
1275
1276 if (isa<DeclRefExpr>(E)) {
1277 return;
1278 }
1279
1280 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1281 Visit(CO->getCond());
1282 CheckLValueToRValueCast(CO->getTrueExpr());
1283 CheckLValueToRValueCast(CO->getFalseExpr());
1284 return;
1285 }
1286
1287 if (BinaryConditionalOperator *BCO =
1288 dyn_cast<BinaryConditionalOperator>(E)) {
1289 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1290 CheckLValueToRValueCast(BCO->getFalseExpr());
1291 return;
1292 }
1293
1294 Visit(E);
1295 }
1296
1297 void VisitDeclRefExpr(DeclRefExpr *E) {
1298 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1299 if (Decls.count(VD))
1300 FoundDecl = true;
1301 }
1302
1303 bool FoundDeclInUse() { return FoundDecl; }
1304
1305 }; // end class DeclMatcher
1306
1307 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1308 Expr *Third, Stmt *Body) {
1309 // Condition is empty
1310 if (!Second) return;
1311
1312 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1313 Second->getLocStart())
1314 == DiagnosticsEngine::Ignored)
1315 return;
1316
1317 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1318 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1319 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001320 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001321 DE.Visit(Second);
1322
1323 // Don't analyze complex conditionals.
1324 if (!DE.isSimple()) return;
1325
1326 // No decls found.
1327 if (Decls.size() == 0) return;
1328
Richard Trieu90875992012-05-04 03:01:54 +00001329 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001330 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1331 E = Decls.end();
1332 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001333 if ((*I)->getType().isVolatileQualified() ||
1334 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001335
1336 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1337 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1338 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1339 return;
1340
1341 // Load decl names into diagnostic.
1342 if (Decls.size() > 4)
1343 PDiag << 0;
1344 else {
1345 PDiag << Decls.size();
1346 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1347 E = Decls.end();
1348 I != E; ++I)
1349 PDiag << (*I)->getDeclName();
1350 }
1351
1352 // Load SourceRanges into diagnostic if there is room.
1353 // Otherwise, load the SourceRange of the conditional expression.
1354 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1355 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1356 E = Ranges.end();
1357 I != E; ++I)
1358 PDiag << *I;
1359 else
1360 PDiag << Second->getSourceRange();
1361
1362 S.Diag(Ranges.begin()->getBegin(), PDiag);
1363 }
1364
1365} // end namespace
1366
John McCall60d7b3a2010-08-24 06:29:42 +00001367StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001368Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001369 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001370 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001371 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001372 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001373 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001374 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1375 // declare identifiers for objects having storage class 'auto' or
1376 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001377 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1378 DI!=DE; ++DI) {
1379 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001380 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001381 VD = 0;
1382 if (VD == 0)
1383 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1384 // FIXME: mark decl erroneous!
1385 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001386 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001388
Richard Trieu694e7962012-04-30 18:01:30 +00001389 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1390
John McCall60d7b3a2010-08-24 06:29:42 +00001391 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001392 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001393 if (secondVar) {
1394 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001395 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001396 if (SecondResult.isInvalid())
1397 return StmtError();
1398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001399
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001400 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001401
Anders Carlsson3af708f2009-08-01 01:39:59 +00001402 DiagnoseUnusedExprResult(First);
1403 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001404 DiagnoseUnusedExprResult(Body);
1405
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001406 if (isa<NullStmt>(Body))
1407 getCurCompoundScope().setHasEmptyLoopBodies();
1408
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409 return Owned(new (Context) ForStmt(Context, First,
1410 SecondResult.take(), ConditionVar,
1411 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001412 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001413}
1414
John McCallf6a16482010-12-04 03:47:34 +00001415/// In an Objective C collection iteration statement:
1416/// for (x in y)
1417/// x can be an arbitrary l-value expression. Bind it up as a
1418/// full-expression.
1419StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001420 // Reduce placeholder expressions here. Note that this rejects the
1421 // use of pseudo-object l-values in this position.
1422 ExprResult result = CheckPlaceholderExpr(E);
1423 if (result.isInvalid()) return StmtError();
1424 E = result.take();
1425
John McCallf6a16482010-12-04 03:47:34 +00001426 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001427
1428 result = MaybeCreateExprWithCleanups(E);
1429 if (result.isInvalid()) return StmtError();
1430
1431 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001432}
1433
John McCall990567c2011-07-27 01:07:15 +00001434ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001435Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1436 if (!collection)
1437 return ExprError();
1438
John McCall990567c2011-07-27 01:07:15 +00001439 // Bail out early if we've got a type-dependent expression.
1440 if (collection->isTypeDependent()) return Owned(collection);
1441
1442 // Perform normal l-value conversion.
1443 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1444 if (result.isInvalid())
1445 return ExprError();
1446 collection = result.take();
1447
1448 // The operand needs to have object-pointer type.
1449 // TODO: should we do a contextual conversion?
1450 const ObjCObjectPointerType *pointerType =
1451 collection->getType()->getAs<ObjCObjectPointerType>();
1452 if (!pointerType)
1453 return Diag(forLoc, diag::err_collection_expr_type)
1454 << collection->getType() << collection->getSourceRange();
1455
1456 // Check that the operand provides
1457 // - countByEnumeratingWithState:objects:count:
1458 const ObjCObjectType *objectType = pointerType->getObjectType();
1459 ObjCInterfaceDecl *iface = objectType->getInterface();
1460
1461 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001462 // Under ARC, it is an error not to have a forward-declared class.
1463 if (iface &&
1464 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001465 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001466 ? diag::err_arc_collection_forward
1467 : 0,
1468 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001469 // Otherwise, if we have any useful type information, check that
1470 // the type declares the appropriate method.
1471 } else if (iface || !objectType->qual_empty()) {
1472 IdentifierInfo *selectorIdents[] = {
1473 &Context.Idents.get("countByEnumeratingWithState"),
1474 &Context.Idents.get("objects"),
1475 &Context.Idents.get("count")
1476 };
1477 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1478
1479 ObjCMethodDecl *method = 0;
1480
1481 // If there's an interface, look in both the public and private APIs.
1482 if (iface) {
1483 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001484 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001485 }
1486
1487 // Also check protocol qualifiers.
1488 if (!method)
1489 method = LookupMethodInQualifiedType(selector, pointerType,
1490 /*instance*/ true);
1491
1492 // If we didn't find it anywhere, give up.
1493 if (!method) {
1494 Diag(forLoc, diag::warn_collection_expr_type)
1495 << collection->getType() << selector << collection->getSourceRange();
1496 }
1497
1498 // TODO: check for an incompatible signature?
1499 }
1500
1501 // Wrap up any cleanups in the expression.
1502 return Owned(MaybeCreateExprWithCleanups(collection));
1503}
1504
John McCall60d7b3a2010-08-24 06:29:42 +00001505StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001506Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1507 SourceLocation LParenLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001508 Stmt *First, Expr *collection,
1509 SourceLocation RParenLoc) {
1510
1511 ExprResult CollectionExprResult =
1512 CheckObjCForCollectionOperand(ForLoc, collection);
1513
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001514 if (First) {
1515 QualType FirstType;
1516 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001517 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001518 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1519 diag::err_toomany_element_decls));
1520
John McCallf85e1932011-06-15 23:02:42 +00001521 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1522 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001523 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1524 // declare identifiers for objects having storage class 'auto' or
1525 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001526 if (!D->hasLocalStorage())
1527 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001528 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001529 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001530 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001531 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001532 return StmtError(Diag(First->getLocStart(),
1533 diag::err_selector_element_not_lvalue)
1534 << First->getSourceRange());
1535
Mike Stump1eb44332009-09-09 15:08:12 +00001536 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001537 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001538 if (!FirstType->isDependentType() &&
1539 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001540 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001541 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1542 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001543 }
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001544
1545 if (CollectionExprResult.isInvalid())
1546 return StmtError();
1547
1548 return Owned(new (Context) ObjCForCollectionStmt(First,
1549 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001550 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001551}
Reid Spencer5f016e22007-07-11 17:01:13 +00001552
Richard Smithad762fc2011-04-14 22:09:26 +00001553namespace {
1554
1555enum BeginEndFunction {
1556 BEF_begin,
1557 BEF_end
1558};
1559
1560/// Build a variable declaration for a for-range statement.
1561static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1562 QualType Type, const char *Name) {
1563 DeclContext *DC = SemaRef.CurContext;
1564 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1565 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1566 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1567 TInfo, SC_Auto, SC_None);
Richard Smithb403d6d2011-04-18 15:49:25 +00001568 Decl->setImplicit();
Richard Smithad762fc2011-04-14 22:09:26 +00001569 return Decl;
1570}
1571
1572/// Finish building a variable declaration for a for-range statement.
1573/// \return true if an error occurs.
1574static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1575 SourceLocation Loc, int diag) {
1576 // Deduce the type for the iterator variable now rather than leaving it to
1577 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1578 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001579 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001580 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1581 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001582 SemaRef.Diag(Loc, diag) << Init->getType();
1583 if (!InitTSI) {
1584 Decl->setInvalidDecl();
1585 return true;
1586 }
1587 Decl->setTypeSourceInfo(InitTSI);
1588 Decl->setType(InitTSI->getType());
1589
John McCallf85e1932011-06-15 23:02:42 +00001590 // In ARC, infer lifetime.
1591 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1592 // we're doing the equivalent of fast iteration.
David Blaikie4e4d0842012-03-11 07:00:24 +00001593 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001594 SemaRef.inferObjCARCLifetime(Decl))
1595 Decl->setInvalidDecl();
1596
Richard Smithad762fc2011-04-14 22:09:26 +00001597 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1598 /*TypeMayContainAuto=*/false);
1599 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001600 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001601 return false;
1602}
1603
1604/// Produce a note indicating which begin/end function was implicitly called
1605/// by a C++0x for-range statement. This is often not obvious from the code,
1606/// nor from the diagnostics produced when analysing the implicit expressions
1607/// required in a for-range statement.
1608void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1609 BeginEndFunction BEF) {
1610 CallExpr *CE = dyn_cast<CallExpr>(E);
1611 if (!CE)
1612 return;
1613 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1614 if (!D)
1615 return;
1616 SourceLocation Loc = D->getLocation();
1617
1618 std::string Description;
1619 bool IsTemplate = false;
1620 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1621 Description = SemaRef.getTemplateArgumentBindingsText(
1622 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1623 IsTemplate = true;
1624 }
1625
1626 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1627 << BEF << IsTemplate << Description << E->getType();
1628}
1629
1630/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1631/// given LookupResult is non-empty, it is assumed to describe a member which
1632/// will be invoked. Otherwise, the function will be found via argument
1633/// dependent lookup.
1634static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1635 SourceLocation Loc,
1636 VarDecl *Decl,
1637 BeginEndFunction BEF,
1638 const DeclarationNameInfo &NameInfo,
1639 LookupResult &MemberLookup,
1640 Expr *Range) {
1641 ExprResult CallExpr;
1642 if (!MemberLookup.empty()) {
1643 ExprResult MemberRef =
1644 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1645 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001646 /*TemplateKWLoc=*/SourceLocation(),
1647 /*FirstQualifierInScope=*/0,
1648 MemberLookup,
Richard Smithad762fc2011-04-14 22:09:26 +00001649 /*TemplateArgs=*/0);
1650 if (MemberRef.isInvalid())
1651 return ExprError();
1652 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1653 Loc, 0);
1654 if (CallExpr.isInvalid())
1655 return ExprError();
1656 } else {
1657 UnresolvedSet<0> FoundNames;
1658 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1659 // std is an associated namespace.
1660 UnresolvedLookupExpr *Fn =
1661 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1662 NestedNameSpecifierLoc(), NameInfo,
1663 /*NeedsADL=*/true, /*Overloaded=*/false,
1664 FoundNames.begin(), FoundNames.end(),
1665 /*LookInStdNamespace=*/true);
1666 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00001667 0, /*AllowTypoCorrection=*/false);
Richard Smithad762fc2011-04-14 22:09:26 +00001668 if (CallExpr.isInvalid()) {
1669 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1670 << Range->getType();
1671 return ExprError();
1672 }
1673 }
1674 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1675 diag::err_for_range_iter_deduction_failure)) {
1676 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1677 return ExprError();
1678 }
1679 return CallExpr;
1680}
1681
1682}
1683
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001684static bool ObjCEnumerationCollection(Expr *Collection) {
1685 return !Collection->isTypeDependent()
1686 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1687}
1688
Richard Smithad762fc2011-04-14 22:09:26 +00001689/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1690///
1691/// C++0x [stmt.ranged]:
1692/// A range-based for statement is equivalent to
1693///
1694/// {
1695/// auto && __range = range-init;
1696/// for ( auto __begin = begin-expr,
1697/// __end = end-expr;
1698/// __begin != __end;
1699/// ++__begin ) {
1700/// for-range-declaration = *__begin;
1701/// statement
1702/// }
1703/// }
1704///
1705/// The body of the loop is not available yet, since it cannot be analysed until
1706/// we have determined the type of the for-range-declaration.
1707StmtResult
1708Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1709 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1710 SourceLocation RParenLoc) {
1711 if (!First || !Range)
1712 return StmtError();
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001713
1714 if (ObjCEnumerationCollection(Range))
1715 return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1716 RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001717
1718 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1719 assert(DS && "first part of for range not a decl stmt");
1720
1721 if (!DS->isSingleDecl()) {
1722 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1723 return StmtError();
1724 }
1725 if (DS->getSingleDecl()->isInvalidDecl())
1726 return StmtError();
1727
1728 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1729 return StmtError();
1730
1731 // Build auto && __range = range-init
1732 SourceLocation RangeLoc = Range->getLocStart();
1733 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1734 Context.getAutoRRefDeductType(),
1735 "__range");
1736 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1737 diag::err_for_range_deduction_failure))
1738 return StmtError();
1739
1740 // Claim the type doesn't contain auto: we've already done the checking.
1741 DeclGroupPtrTy RangeGroup =
1742 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1743 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1744 if (RangeDecl.isInvalid())
1745 return StmtError();
1746
1747 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1748 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1749 RParenLoc);
1750}
1751
1752/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1753StmtResult
1754Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1755 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1756 Expr *Inc, Stmt *LoopVarDecl,
1757 SourceLocation RParenLoc) {
1758 Scope *S = getCurScope();
1759
1760 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1761 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1762 QualType RangeVarType = RangeVar->getType();
1763
1764 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1765 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1766
1767 StmtResult BeginEndDecl = BeginEnd;
1768 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1769
1770 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1771 SourceLocation RangeLoc = RangeVar->getLocation();
1772
Ted Kremeneke50b0152011-10-10 22:36:28 +00001773 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1774
1775 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1776 VK_LValue, ColonLoc);
1777 if (BeginRangeRef.isInvalid())
1778 return StmtError();
1779
1780 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1781 VK_LValue, ColonLoc);
1782 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001783 return StmtError();
1784
1785 QualType AutoType = Context.getAutoDeductType();
1786 Expr *Range = RangeVar->getInit();
1787 if (!Range)
1788 return StmtError();
1789 QualType RangeType = Range->getType();
1790
1791 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001792 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001793 return StmtError();
1794
1795 // Build auto __begin = begin-expr, __end = end-expr.
1796 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1797 "__begin");
1798 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1799 "__end");
1800
1801 // Build begin-expr and end-expr and attach to __begin and __end variables.
1802 ExprResult BeginExpr, EndExpr;
1803 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1804 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1805 // __range + __bound, respectively, where __bound is the array bound. If
1806 // _RangeT is an array of unknown size or an array of incomplete type,
1807 // the program is ill-formed;
1808
1809 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001810 BeginExpr = BeginRangeRef;
1811 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001812 diag::err_for_range_iter_deduction_failure)) {
1813 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1814 return StmtError();
1815 }
1816
1817 // Find the array bound.
1818 ExprResult BoundExpr;
1819 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1820 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001821 Context.getPointerDiffType(),
1822 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001823 else if (const VariableArrayType *VAT =
1824 dyn_cast<VariableArrayType>(UnqAT))
1825 BoundExpr = VAT->getSizeExpr();
1826 else {
1827 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1828 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001829 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001830 }
1831
1832 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001833 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001834 BoundExpr.get());
1835 if (EndExpr.isInvalid())
1836 return StmtError();
1837 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1838 diag::err_for_range_iter_deduction_failure)) {
1839 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1840 return StmtError();
1841 }
1842 } else {
1843 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1844 ColonLoc);
1845 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1846 ColonLoc);
1847
1848 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1849 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1850
1851 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1852 // - if _RangeT is a class type, the unqualified-ids begin and end are
1853 // looked up in the scope of class _RangeT as if by class member access
1854 // lookup (3.4.5), and if either (or both) finds at least one
1855 // declaration, begin-expr and end-expr are __range.begin() and
1856 // __range.end(), respectively;
1857 LookupQualifiedName(BeginMemberLookup, D);
1858 LookupQualifiedName(EndMemberLookup, D);
1859
1860 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1861 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1862 << RangeType << BeginMemberLookup.empty();
1863 return StmtError();
1864 }
1865 } else {
1866 // - otherwise, begin-expr and end-expr are begin(__range) and
1867 // end(__range), respectively, where begin and end are looked up with
1868 // argument-dependent lookup (3.4.2). For the purposes of this name
1869 // lookup, namespace std is an associated namespace.
1870 }
1871
1872 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1873 BEF_begin, BeginNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001874 BeginMemberLookup,
1875 BeginRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001876 if (BeginExpr.isInvalid())
1877 return StmtError();
1878
1879 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1880 BEF_end, EndNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001881 EndMemberLookup, EndRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001882 if (EndExpr.isInvalid())
1883 return StmtError();
1884 }
1885
1886 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1887 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1888 if (!Context.hasSameType(BeginType, EndType)) {
1889 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1890 << BeginType << EndType;
1891 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1892 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1893 }
1894
1895 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1896 // Claim the type doesn't contain auto: we've already done the checking.
1897 DeclGroupPtrTy BeginEndGroup =
1898 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1899 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1900
Ted Kremeneke50b0152011-10-10 22:36:28 +00001901 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1902 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001903 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001904 if (BeginRef.isInvalid())
1905 return StmtError();
1906
Richard Smithad762fc2011-04-14 22:09:26 +00001907 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1908 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001909 if (EndRef.isInvalid())
1910 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001911
1912 // Build and check __begin != __end expression.
1913 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1914 BeginRef.get(), EndRef.get());
1915 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1916 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1917 if (NotEqExpr.isInvalid()) {
1918 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1919 if (!Context.hasSameType(BeginType, EndType))
1920 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1921 return StmtError();
1922 }
1923
1924 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001925 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1926 VK_LValue, ColonLoc);
1927 if (BeginRef.isInvalid())
1928 return StmtError();
1929
Richard Smithad762fc2011-04-14 22:09:26 +00001930 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1931 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1932 if (IncrExpr.isInvalid()) {
1933 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1934 return StmtError();
1935 }
1936
1937 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001938 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1939 VK_LValue, ColonLoc);
1940 if (BeginRef.isInvalid())
1941 return StmtError();
1942
Richard Smithad762fc2011-04-14 22:09:26 +00001943 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1944 if (DerefExpr.isInvalid()) {
1945 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1946 return StmtError();
1947 }
1948
1949 // Attach *__begin as initializer for VD.
1950 if (!LoopVar->isInvalidDecl()) {
1951 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1952 /*TypeMayContainAuto=*/true);
1953 if (LoopVar->isInvalidDecl())
1954 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1955 }
Richard Smithcd6f3662011-06-21 23:07:19 +00001956 } else {
1957 // The range is implicitly used as a placeholder when it is dependent.
1958 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00001959 }
1960
1961 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1962 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1963 NotEqExpr.take(), IncrExpr.take(),
1964 LoopVarDS, /*Body=*/0, ForLoc,
1965 ColonLoc, RParenLoc));
1966}
1967
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001968/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1969/// statement.
1970StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1971 if (!S || !B)
1972 return StmtError();
1973 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1974
1975 ForStmt->setBody(B);
1976 return S;
1977}
1978
Richard Smithad762fc2011-04-14 22:09:26 +00001979/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1980/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1981/// body cannot be performed until after the type of the range variable is
1982/// determined.
1983StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1984 if (!S || !B)
1985 return StmtError();
1986
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001987 if (isa<ObjCForCollectionStmt>(S))
1988 return FinishObjCForCollectionStmt(S, B);
1989
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001990 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1991 ForStmt->setBody(B);
1992
1993 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1994 diag::warn_empty_range_based_for_body);
1995
Richard Smithad762fc2011-04-14 22:09:26 +00001996 return S;
1997}
1998
Chris Lattner57ad3782011-02-17 20:34:02 +00001999StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2000 SourceLocation LabelLoc,
2001 LabelDecl *TheDecl) {
2002 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002003 TheDecl->setUsed();
2004 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002005}
2006
John McCall60d7b3a2010-08-24 06:29:42 +00002007StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002008Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002009 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002010 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002011 if (!E->isTypeDependent()) {
2012 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002013 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002014 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002015 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002016 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2017 if (ExprRes.isInvalid())
2018 return StmtError();
2019 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002020 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002021 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00002022 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002023 }
John McCallb60a77e2010-08-01 00:26:45 +00002024
John McCall781472f2010-08-25 08:40:02 +00002025 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002026
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002027 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002028}
2029
John McCall60d7b3a2010-08-24 06:29:42 +00002030StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002031Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 Scope *S = CurScope->getContinueParent();
2033 if (!S) {
2034 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002035 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002037
Ted Kremenek8189cde2009-02-07 01:47:29 +00002038 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002039}
2040
John McCall60d7b3a2010-08-24 06:29:42 +00002041StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002042Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 Scope *S = CurScope->getBreakParent();
2044 if (!S) {
2045 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002046 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002048
Ted Kremenek8189cde2009-02-07 01:47:29 +00002049 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002050}
2051
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002052/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002053/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002054///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002055/// \param ReturnType If we're determining the copy elision candidate for
2056/// a return statement, this is the return type of the function. If we're
2057/// determining the copy elision candidate for a throw expression, this will
2058/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002059///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002060/// \param E The expression being returned from the function or block, or
2061/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002062///
Douglas Gregor4926d832011-05-20 15:00:53 +00002063/// \param AllowFunctionParameter Whether we allow function parameters to
2064/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2065/// we re-use this logic to determine whether we should try to move as part of
2066/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002067///
2068/// \returns The NRVO candidate variable, if the return statement may use the
2069/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002070const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2071 Expr *E,
2072 bool AllowFunctionParameter) {
2073 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002074 // - in a return statement in a function with ...
2075 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002076 if (!ReturnType.isNull()) {
2077 if (!ReturnType->isRecordType())
2078 return 0;
2079 // ... the same cv-unqualified type as the function return type ...
2080 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2081 return 0;
2082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002083
2084 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002085 // (other than a function or catch-clause parameter)) ...
2086 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002087 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002088 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002089 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2090 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002091 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002092
John McCall1cd76e82011-11-11 03:57:31 +00002093 // ...object (other than a function or catch-clause parameter)...
2094 if (VD->getKind() != Decl::Var &&
2095 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2096 return 0;
2097 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002098
John McCall1cd76e82011-11-11 03:57:31 +00002099 // ...automatic...
2100 if (!VD->hasLocalStorage()) return 0;
2101
2102 // ...non-volatile...
2103 if (VD->getType().isVolatileQualified()) return 0;
2104 if (VD->getType()->isReferenceType()) return 0;
2105
2106 // __block variables can't be allocated in a way that permits NRVO.
2107 if (VD->hasAttr<BlocksAttr>()) return 0;
2108
2109 // Variables with higher required alignment than their type's ABI
2110 // alignment cannot use NRVO.
2111 if (VD->hasAttr<AlignedAttr>() &&
2112 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2113 return 0;
2114
2115 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002116}
2117
Douglas Gregor07f402c2011-01-21 21:08:57 +00002118/// \brief Perform the initialization of a potentially-movable value, which
2119/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002120///
2121/// This routine implements C++0x [class.copy]p33, which attempts to treat
2122/// returned lvalues as rvalues in certain cases (to prefer move construction),
2123/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002125Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2126 const VarDecl *NRVOCandidate,
2127 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002128 Expr *Value,
2129 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002130 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002131 // When the criteria for elision of a copy operation are met or would
2132 // be met save for the fact that the source object is a function
2133 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002134 // overload resolution to select the constructor for the copy is first
2135 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002136 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002137 if (AllowNRVO &&
2138 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002139 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002140 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141
Douglas Gregorcc15f012011-01-21 19:38:21 +00002142 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002144 = InitializationKind::CreateCopy(Value->getLocStart(),
2145 Value->getLocStart());
2146 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002147
2148 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002149 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002150 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002151 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002152 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002153 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2154 StepEnd = Seq.step_end();
2155 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002156 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002157 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
2159 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002160 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161
Douglas Gregorcc15f012011-01-21 19:38:21 +00002162 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002163 = Constructor->getParamDecl(0)->getType()
2164 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002165
Douglas Gregorcc15f012011-01-21 19:38:21 +00002166 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002167 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002168 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2169 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002170 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171
Douglas Gregorcc15f012011-01-21 19:38:21 +00002172 // Promote "AsRvalue" to the heap, since we now need this
2173 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002174 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002175 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002176
Douglas Gregorcc15f012011-01-21 19:38:21 +00002177 // Complete type-checking the initialization of the return type
2178 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002179 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002180 }
2181 }
2182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183
Douglas Gregorcc15f012011-01-21 19:38:21 +00002184 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002186 // (again) now with the return value expression as written.
2187 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002188 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002189
Douglas Gregorcc15f012011-01-21 19:38:21 +00002190 return Res;
2191}
2192
Eli Friedman84b007f2012-01-26 03:00:14 +00002193/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2194/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002195///
John McCall60d7b3a2010-08-24 06:29:42 +00002196StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002197Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2198 // If this is the first return we've seen, infer the return type.
2199 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2200 // rules which allows multiple return statements.
2201 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002202 QualType FnRetType = CurCap->ReturnType;
2203
2204 // For blocks/lambdas with implicit return types, we check each return
2205 // statement individually, and deduce the common return type when the block
2206 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002207 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002208 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002209 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2210 if (Result.isInvalid())
2211 return StmtError();
2212 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002213
Jordan Rose7dd900e2012-07-02 21:19:23 +00002214 if (!RetValExp->isTypeDependent())
2215 FnRetType = RetValExp->getType();
2216 else
2217 FnRetType = CurCap->ReturnType = Context.DependentTy;
Douglas Gregora0c2b212012-02-09 18:40:39 +00002218 } else {
2219 if (RetValExp) {
2220 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2221 // initializer list, because it is not an expression (even
2222 // though we represent it as one). We still deduce 'void'.
2223 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2224 << RetValExp->getSourceRange();
2225 }
2226
Jordan Rose7dd900e2012-07-02 21:19:23 +00002227 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002228 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002229
2230 // Although we'll properly infer the type of the block once it's completed,
2231 // make sure we provide a return type now for better error recovery.
2232 if (CurCap->ReturnType.isNull())
2233 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002234 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002235 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002236
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002237 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002238 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2239 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2240 return StmtError();
2241 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002242 } else {
2243 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2244 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2245 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2246 return StmtError();
2247 }
2248 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002249
Steve Naroff4eb206b2008-09-03 18:15:37 +00002250 // Otherwise, verify that this result type matches the previous one. We are
2251 // pickier with blocks than for normal functions because we don't have GCC
2252 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002253 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002254 if (FnRetType->isDependentType()) {
2255 // Delay processing for now. TODO: there are lots of dependent
2256 // types we can conclusively prove aren't void.
2257 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002258 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002259 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002260 (RetValExp->isTypeDependent() ||
2261 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002262 if (!getLangOpts().CPlusPlus &&
2263 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002264 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002265 else {
2266 Diag(ReturnLoc, diag::err_return_block_has_expr);
2267 RetValExp = 0;
2268 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002269 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002270 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002271 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2272 } else if (!RetValExp->isTypeDependent()) {
2273 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002274
John McCall0a7efe12011-08-17 22:09:46 +00002275 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2276 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2277 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002278
John McCall0a7efe12011-08-17 22:09:46 +00002279 // In C++ the return statement is handled via a copy initialization.
2280 // the C version of which boils down to CheckSingleAssignmentConstraints.
2281 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2282 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2283 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002284 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002285 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2286 FnRetType, RetValExp);
2287 if (Res.isInvalid()) {
2288 // FIXME: Cleanup temporaries here, anyway?
2289 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002290 }
John McCall0a7efe12011-08-17 22:09:46 +00002291 RetValExp = Res.take();
2292 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002293 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002294
John McCalld963c372011-08-17 21:34:14 +00002295 if (RetValExp) {
2296 CheckImplicitConversions(RetValExp, ReturnLoc);
2297 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2298 }
John McCall0a7efe12011-08-17 22:09:46 +00002299 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2300 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002301
Jordan Rose7dd900e2012-07-02 21:19:23 +00002302 // If we need to check for the named return value optimization,
2303 // or if we need to infer the return type,
2304 // save the return statement in our scope for later processing.
2305 if (CurCap->HasImplicitReturnType ||
2306 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2307 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002308 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002309
Douglas Gregor5077c382010-05-15 06:01:05 +00002310 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002311}
Reid Spencer5f016e22007-07-11 17:01:13 +00002312
John McCall60d7b3a2010-08-24 06:29:42 +00002313StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002314Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002315 // Check for unexpanded parameter packs.
2316 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2317 return StmtError();
2318
Eli Friedman84b007f2012-01-26 03:00:14 +00002319 if (isa<CapturingScopeInfo>(getCurFunction()))
2320 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002321
Chris Lattner371f2582008-12-04 23:50:19 +00002322 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002323 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002324 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002325 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002326 if (FD->hasAttr<NoReturnAttr>() ||
2327 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002328 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002329 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002330 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002331 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002332 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2333 // In the implementation of a method with a related return type, the
2334 // type used to type-check the validity of return statements within the
2335 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002336 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2337 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002338 }
2339 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002340 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Douglas Gregor5077c382010-05-15 06:01:05 +00002342 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002343 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002344 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002345 if (isa<InitListExpr>(RetValExp)) {
2346 // We simply never allow init lists as the return value of void
2347 // functions. This is compatible because this was never allowed before,
2348 // so there's no legacy code to deal with.
2349 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2350 int FunctionKind = 0;
2351 if (isa<ObjCMethodDecl>(CurDecl))
2352 FunctionKind = 1;
2353 else if (isa<CXXConstructorDecl>(CurDecl))
2354 FunctionKind = 2;
2355 else if (isa<CXXDestructorDecl>(CurDecl))
2356 FunctionKind = 3;
2357
2358 Diag(ReturnLoc, diag::err_return_init_list)
2359 << CurDecl->getDeclName() << FunctionKind
2360 << RetValExp->getSourceRange();
2361
2362 // Drop the expression.
2363 RetValExp = 0;
2364 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002365 // C99 6.8.6.4p1 (ext_ since GCC warns)
2366 unsigned D = diag::ext_return_has_expr;
2367 if (RetValExp->getType()->isVoidType())
2368 D = diag::ext_return_has_void_expr;
2369 else {
2370 ExprResult Result = Owned(RetValExp);
2371 Result = IgnoredValueConversions(Result.take());
2372 if (Result.isInvalid())
2373 return StmtError();
2374 RetValExp = Result.take();
2375 RetValExp = ImpCastExprToType(RetValExp,
2376 Context.VoidTy, CK_ToVoid).take();
2377 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002378
Nick Lewycky8d794612011-06-01 07:44:31 +00002379 // return (some void expression); is legal in C++.
2380 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002381 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002382 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002383
2384 int FunctionKind = 0;
2385 if (isa<ObjCMethodDecl>(CurDecl))
2386 FunctionKind = 1;
2387 else if (isa<CXXConstructorDecl>(CurDecl))
2388 FunctionKind = 2;
2389 else if (isa<CXXDestructorDecl>(CurDecl))
2390 FunctionKind = 3;
2391
Nick Lewycky8d794612011-06-01 07:44:31 +00002392 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002393 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002394 << RetValExp->getSourceRange();
2395 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Sebastian Redl33deb352012-02-22 10:50:08 +00002398 if (RetValExp) {
2399 CheckImplicitConversions(RetValExp, ReturnLoc);
2400 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002403
Douglas Gregor5077c382010-05-15 06:01:05 +00002404 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2405 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002406 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2407 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002408 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002409
2410 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002411 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002412 else
Chris Lattner08631c52008-11-23 21:45:46 +00002413 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002414 Result = new (Context) ReturnStmt(ReturnLoc);
2415 } else {
2416 const VarDecl *NRVOCandidate = 0;
2417 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2418 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002419
Eli Friedman38ac2432012-03-30 01:13:43 +00002420 if (!RelatedRetType.isNull()) {
2421 // If we have a related result type, perform an extra conversion here.
2422 // FIXME: The diagnostics here don't really describe what is happening.
2423 InitializedEntity Entity =
2424 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002425
Eli Friedman38ac2432012-03-30 01:13:43 +00002426 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2427 RetValExp);
2428 if (Res.isInvalid()) {
2429 // FIXME: Cleanup temporaries here, anyway?
2430 return StmtError();
2431 }
2432 RetValExp = Res.takeAs<Expr>();
2433 }
2434
Douglas Gregor5077c382010-05-15 06:01:05 +00002435 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2436 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2437 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002438
John McCall856d3792011-06-16 23:24:51 +00002439 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002440 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002441 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002442 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002443 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002444 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002445 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002446 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002447 if (Res.isInvalid()) {
2448 // FIXME: Cleanup temporaries here, anyway?
2449 return StmtError();
2450 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002451
Douglas Gregor5077c382010-05-15 06:01:05 +00002452 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002453 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002454 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002455 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002456
John McCallb4eb64d2010-10-08 02:01:28 +00002457 if (RetValExp) {
2458 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002459 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002460 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002461 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002463
2464 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002465 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002466 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002467 !CurContext->isDependentContext())
2468 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002469
Douglas Gregor5077c382010-05-15 06:01:05 +00002470 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002471}
2472
Chris Lattner810f6d52009-03-13 17:38:01 +00002473/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2474/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2475/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2476/// provide a strong guidance to not use it.
2477///
2478/// This method checks to see if the argument is an acceptable l-value and
2479/// returns false if it is a case we can handle.
2480static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00002481 // Type dependent expressions will be checked during instantiation.
2482 if (E->isTypeDependent())
2483 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002484
John McCall7eb0a9e2010-11-24 05:12:34 +00002485 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00002486 return false; // Cool, this is an lvalue.
2487
2488 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2489 // are supposed to allow.
2490 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00002491 if (E != E2 && E2->isLValue()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002492 if (!S.getLangOpts().HeinousExtensions)
Chris Lattner810f6d52009-03-13 17:38:01 +00002493 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2494 << E->getSourceRange();
2495 else
2496 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2497 << E->getSourceRange();
2498 // Accept, even if we emitted an error diagnostic.
2499 return false;
2500 }
2501
2502 // None of the above, just randomly invalid non-lvalue.
2503 return true;
2504}
2505
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002506/// isOperandMentioned - Return true if the specified operand # is mentioned
2507/// anywhere in the decomposed asm string.
2508static bool isOperandMentioned(unsigned OpNo,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002509 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002510 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2511 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2512 if (!Piece.isOperand()) continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002513
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002514 // If this is a reference to the input and if the input was the smaller
2515 // one, then we have to reject this asm.
2516 if (Piece.getOperandNo() == OpNo)
2517 return true;
2518 }
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002519 return false;
2520}
Chris Lattner810f6d52009-03-13 17:38:01 +00002521
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002522StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2523 bool IsVolatile, unsigned NumOutputs,
2524 unsigned NumInputs, IdentifierInfo **Names,
2525 MultiExprArg constraints, MultiExprArg exprs,
2526 Expr *asmString, MultiExprArg clobbers,
2527 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002528 unsigned NumClobbers = clobbers.size();
2529 StringLiteral **Constraints =
2530 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00002531 Expr **Exprs = exprs.get();
2532 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00002533 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2534
Chris Lattner5f9e2722011-07-23 10:55:15 +00002535 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Chris Lattner1708b962008-08-18 19:55:17 +00002537 // The parser verifies that there is a string literal here.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002538 if (!AsmString->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002539 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2540 << AsmString->getSourceRange());
2541
Chris Lattner1708b962008-08-18 19:55:17 +00002542 for (unsigned i = 0; i != NumOutputs; i++) {
2543 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002544 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002545 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2546 << Literal->getSourceRange());
2547
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548 StringRef OutputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002549 if (Names[i])
2550 OutputName = Names[i]->getName();
2551
2552 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002553 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002554 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002555 diag::err_asm_invalid_output_constraint)
2556 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00002557
Anders Carlssond04c6e22007-11-27 04:11:28 +00002558 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00002559 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00002560 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00002561 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002562 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00002563 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002564 }
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Chris Lattner44def072009-04-26 07:16:29 +00002566 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002567 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002568
Chris Lattner5f9e2722011-07-23 10:55:15 +00002569 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner806503f2009-05-03 05:55:43 +00002570
Anders Carlsson04728b72007-11-23 19:43:50 +00002571 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00002572 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002573 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002574 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2575 << Literal->getSourceRange());
2576
Chris Lattner5f9e2722011-07-23 10:55:15 +00002577 StringRef InputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002578 if (Names[i])
2579 InputName = Names[i]->getName();
2580
2581 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002582 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00002583 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002584 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002585 diag::err_asm_invalid_input_constraint)
2586 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00002587 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002588
Eli Friedman72056a22009-05-03 07:49:42 +00002589 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00002590
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002591 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00002592 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00002593 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00002594 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002595 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00002596 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002597 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002598 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002599
Chris Lattner44def072009-04-26 07:16:29 +00002600 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002601 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00002602 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002603 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00002604 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002605 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002606 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002607 }
Mike Stump1eb44332009-09-09 15:08:12 +00002608
John Wiegley429bb272011-04-08 18:41:53 +00002609 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2610 if (Result.isInvalid())
2611 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002612
John Wiegley429bb272011-04-08 18:41:53 +00002613 Exprs[i] = Result.take();
Chris Lattner806503f2009-05-03 05:55:43 +00002614 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002615 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002616
Anders Carlsson6fa90862007-11-25 00:25:21 +00002617 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00002618 for (unsigned i = 0; i != NumClobbers; i++) {
2619 StringLiteral *Literal = Clobbers[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002620 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002621 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2622 << Literal->getSourceRange());
2623
Chris Lattner5f9e2722011-07-23 10:55:15 +00002624 StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00002625
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002626 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002627 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00002628 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00002629 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002630
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002631 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002632 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2633 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00002634 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002635 // Validate the asm string, ensuring it makes sense given the operands we
2636 // have.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002637 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002638 unsigned DiagOffs;
2639 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00002640 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2641 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002642 return StmtError();
2643 }
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Chris Lattner806503f2009-05-03 05:55:43 +00002645 // Validate tied input operands for type mismatches.
2646 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2647 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Chris Lattner806503f2009-05-03 05:55:43 +00002649 // If this is a tied constraint, verify that the output and input have
2650 // either exactly the same type, or that they are int/ptr operands with the
2651 // same size (int/long, int*/long, are ok etc).
2652 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Chris Lattner806503f2009-05-03 05:55:43 +00002654 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner935f0f02011-02-21 22:09:29 +00002655 unsigned InputOpNo = i+NumOutputs;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00002656 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner935f0f02011-02-21 22:09:29 +00002657 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedmanf45b3572011-09-14 19:20:00 +00002658
2659 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2660 continue;
2661
Chris Lattner7adaa182009-05-03 05:59:17 +00002662 QualType InTy = InputExpr->getType();
2663 QualType OutTy = OutputExpr->getType();
2664 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00002665 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Chris Lattneraab64d02010-04-23 17:27:29 +00002667 // Decide if the input and output are in the same domain (integer/ptr or
2668 // floating point.
2669 enum AsmDomain {
2670 AD_Int, AD_FP, AD_Other
2671 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672
Chris Lattneraab64d02010-04-23 17:27:29 +00002673 if (InTy->isIntegerType() || InTy->isPointerType())
2674 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002675 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002676 InputDomain = AD_FP;
2677 else
2678 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Chris Lattneraab64d02010-04-23 17:27:29 +00002680 if (OutTy->isIntegerType() || OutTy->isPointerType())
2681 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002682 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002683 OutputDomain = AD_FP;
2684 else
2685 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686
Chris Lattneraab64d02010-04-23 17:27:29 +00002687 // They are ok if they are the same size and in the same domain. This
2688 // allows tying things like:
2689 // void* to int*
2690 // void* to int if they are the same size.
2691 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 //
Chris Lattneraab64d02010-04-23 17:27:29 +00002693 uint64_t OutSize = Context.getTypeSize(OutTy);
2694 uint64_t InSize = Context.getTypeSize(InTy);
2695 if (OutSize == InSize && InputDomain == OutputDomain &&
2696 InputDomain != AD_Other)
2697 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002698
Chris Lattneraab64d02010-04-23 17:27:29 +00002699 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002700 // then we can promote the smaller one to a larger input and the asm string
2701 // won't notice.
Chris Lattneraab64d02010-04-23 17:27:29 +00002702 bool SmallerValueMentioned = false;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002703
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002704 // If this is a reference to the input and if the input was the smaller
2705 // one, then we have to reject this asm.
Chris Lattner935f0f02011-02-21 22:09:29 +00002706 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002707 // This is a use in the asm string of the smaller operand. Since we
2708 // codegen this by promoting to a wider value, the asm will get printed
2709 // "wrong".
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002710 SmallerValueMentioned |= InSize < OutSize;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002711 }
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002712 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002713 // If this is a reference to the output, and if the output is the larger
2714 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002715 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner806503f2009-05-03 05:55:43 +00002716 }
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Chris Lattneraab64d02010-04-23 17:27:29 +00002718 // If the smaller value wasn't mentioned in the asm string, and if the
2719 // output was a register, just extend the shorter one to the size of the
2720 // larger one.
2721 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2722 OutputConstraintInfos[TiedTo].allowsRegister())
2723 continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002724
Chris Lattner935f0f02011-02-21 22:09:29 +00002725 // Either both of the operands were mentioned or the smaller one was
2726 // mentioned. One more special case that we'll allow: if the tied input is
2727 // integer, unmentioned, and is a constant, then we'll allow truncating it
2728 // down to the size of the destination.
2729 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2730 !isOperandMentioned(InputOpNo, Pieces) &&
2731 InputExpr->isEvaluatable(Context)) {
John McCall4da89c82011-05-10 23:39:47 +00002732 CastKind castKind =
2733 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2734 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner935f0f02011-02-21 22:09:29 +00002735 Exprs[InputOpNo] = InputExpr;
2736 NS->setInputExpr(i, InputExpr);
2737 continue;
2738 }
Chad Rosier8e1e0542012-06-20 18:51:04 +00002739
Chris Lattnerc1f3b282009-05-03 06:50:40 +00002740 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00002741 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00002742 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00002743 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00002744 return StmtError();
2745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002747 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00002748}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002749
Chad Rosiere696b692012-08-08 18:22:06 +00002750// needSpaceAsmToken - This function handles whitespace around asm punctuation.
2751// Returns true if a space should be emitted.
Chad Rosiere696b692012-08-08 18:22:06 +00002752static inline bool needSpaceAsmToken(Token currTok) {
2753 static Token prevTok;
2754
2755 // No need for space after prevToken.
2756 switch(prevTok.getKind()) {
2757 default:
2758 break;
2759 case tok::l_square:
2760 case tok::r_square:
2761 case tok::l_brace:
2762 case tok::r_brace:
2763 case tok::colon:
2764 prevTok = currTok;
2765 return false;
2766 }
2767
2768 // No need for a space before currToken.
2769 switch(currTok.getKind()) {
2770 default:
2771 break;
2772 case tok::l_square:
2773 case tok::r_square:
2774 case tok::l_brace:
2775 case tok::r_brace:
2776 case tok::comma:
2777 case tok::colon:
2778 prevTok = currTok;
2779 return false;
2780 }
2781 prevTok = currTok;
2782 return true;
2783}
2784
2785static std::string PatchMSAsmString(Sema &SemaRef, bool &IsSimple,
2786 SourceLocation AsmLoc,
2787 ArrayRef<Token> AsmToks,
2788 const TargetInfo &TI) {
2789 std::string Res;
2790 IdentifierInfo *II = AsmToks[0].getIdentifierInfo();
2791 Res = II->getName().str();
2792
2793 // Assume simple asm stmt until we parse a non-register identifer.
2794 IsSimple = true;
2795
2796 // Check the operands.
2797 for (unsigned i = 1, e = AsmToks.size(); i != e; ++i) {
2798 if (needSpaceAsmToken(AsmToks[i]))
2799 Res += " ";
2800
2801 switch (AsmToks[i].getKind()) {
2802 default:
2803 //llvm_unreachable("Unknown token.");
2804 break;
2805 case tok::comma: Res += ","; break;
2806 case tok::colon: Res += ":"; break;
2807 case tok::l_square: Res += "["; break;
2808 case tok::r_square: Res += "]"; break;
2809 case tok::l_brace: Res += "{"; break;
2810 case tok::r_brace: Res += "}"; break;
2811 case tok::numeric_constant: {
2812 SmallString<32> TokenBuf;
2813 TokenBuf.resize(32);
2814 bool StringInvalid = false;
2815 const char *ThisTokBuf = &TokenBuf[0];
2816 unsigned ThisTokLen =
2817 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2818 SemaRef.getLangOpts(), &StringInvalid);
2819 Res += StringRef(ThisTokBuf, ThisTokLen);
2820 break;
2821 }
2822 case tok::identifier: {
2823 II = AsmToks[i].getIdentifierInfo();
2824 StringRef Name = II->getName();
2825
2826 // Valid registers don't need modification.
2827 if (TI.isValidGCCRegisterName(Name)) {
2828 Res += Name;
2829 break;
2830 }
2831
2832 // TODO: Lookup the identifier.
2833 IsSimple = false;
2834 }
2835 } // AsmToks[i].getKind()
2836 }
2837 return Res;
2838}
2839
Chad Rosier62f22b82012-08-08 19:48:07 +00002840// Build the unmodified MSAsmString.
2841static std::string buildMSAsmString(Sema &SemaRef,
2842 ArrayRef<Token> AsmToks,
2843 ArrayRef<unsigned> LineEnds) {
2844 // Collect the tokens into a string
2845 SmallString<512> Asm;
2846 SmallString<512> TokenBuf;
2847 TokenBuf.resize(512);
2848 unsigned AsmLineNum = 0;
2849 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2850 const char *ThisTokBuf = &TokenBuf[0];
2851 bool StringInvalid = false;
2852 unsigned ThisTokLen =
2853 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2854 SemaRef.getLangOpts(), &StringInvalid);
2855 if (i && (!AsmLineNum || i != LineEnds[AsmLineNum-1]) &&
2856 needSpaceAsmToken(AsmToks[i]))
2857 Asm += ' ';
2858 Asm += StringRef(ThisTokBuf, ThisTokLen);
2859 if (i + 1 == LineEnds[AsmLineNum] && i + 1 != AsmToks.size()) {
2860 Asm += '\n';
2861 ++AsmLineNum;
2862 }
2863 }
2864 return Asm.c_str();
2865}
2866
Chad Rosier8cd64b42012-06-11 20:47:18 +00002867StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
Chad Rosier79efe242012-08-07 00:29:06 +00002868 ArrayRef<Token> AsmToks,
Chad Rosier62f22b82012-08-08 19:48:07 +00002869 ArrayRef<unsigned> LineEnds,
Chad Rosier8cd64b42012-06-11 20:47:18 +00002870 SourceLocation EndLoc) {
Chad Rosier52e4ed92012-06-20 18:28:37 +00002871 // MS-style inline assembly is not fully supported, so emit a warning.
2872 Diag(AsmLoc, diag::warn_unsupported_msasm);
2873
Chad Rosier62f22b82012-08-08 19:48:07 +00002874 std::string AsmString = buildMSAsmString(*this, AsmToks, LineEnds);
2875
Chad Rosiere696b692012-08-08 18:22:06 +00002876 bool IsSimple;
2877 // Rewrite operands to appease the AsmParser.
2878 std::string PatchedAsmString =
2879 PatchMSAsmString(*this, IsSimple, AsmLoc, AsmToks, Context.getTargetInfo());
2880
2881 // Silence compiler warnings. Eventually, the PatchedAsmString will be
2882 // passed to the AsmParser.
2883 (void)PatchedAsmString;
2884
Chad Rosier8cd64b42012-06-11 20:47:18 +00002885 MSAsmStmt *NS =
Chad Rosiere696b692012-08-08 18:22:06 +00002886 new (Context) MSAsmStmt(Context, AsmLoc, IsSimple, /* IsVolatile */ true,
Chad Rosier62f22b82012-08-08 19:48:07 +00002887 AsmToks, LineEnds, AsmString, EndLoc);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002888
2889 return Owned(NS);
2890}
2891
John McCall60d7b3a2010-08-24 06:29:42 +00002892StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002893Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002894 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002895 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002896 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002897 if (Var && Var->isInvalidDecl())
2898 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002899
John McCall9ae2f072010-08-23 23:25:46 +00002900 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002901}
2902
John McCall60d7b3a2010-08-24 06:29:42 +00002903StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002904Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2905 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002906}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002907
John McCall60d7b3a2010-08-24 06:29:42 +00002908StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002909Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002910 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002911 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002912 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2913
John McCall781472f2010-08-25 08:40:02 +00002914 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002915 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002916 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2917 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002918 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002919 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002920}
2921
John McCalld1376ee2012-05-08 21:41:25 +00002922StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002923 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002924 ExprResult Result = DefaultLvalueConversion(Throw);
2925 if (Result.isInvalid())
2926 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002927
John McCalld1376ee2012-05-08 21:41:25 +00002928 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002929 QualType ThrowType = Throw->getType();
2930 // Make sure the expression type is an ObjC pointer or "void *".
2931 if (!ThrowType->isDependentType() &&
2932 !ThrowType->isObjCObjectPointerType()) {
2933 const PointerType *PT = ThrowType->getAs<PointerType>();
2934 if (!PT || !PT->getPointeeType()->isVoidType())
2935 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2936 << Throw->getType() << Throw->getSourceRange());
2937 }
2938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002939
John McCall9ae2f072010-08-23 23:25:46 +00002940 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002941}
2942
John McCall60d7b3a2010-08-24 06:29:42 +00002943StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002944Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002945 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002946 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002947 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2948
John McCall9ae2f072010-08-23 23:25:46 +00002949 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002950 // @throw without an expression designates a rethrow (which much occur
2951 // in the context of an @catch clause).
2952 Scope *AtCatchParent = CurScope;
2953 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2954 AtCatchParent = AtCatchParent->getParent();
2955 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002956 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957 }
John McCall9ae2f072010-08-23 23:25:46 +00002958 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002959}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002960
John McCall07524032011-07-27 21:50:02 +00002961ExprResult
2962Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2963 ExprResult result = DefaultLvalueConversion(operand);
2964 if (result.isInvalid())
2965 return ExprError();
2966 operand = result.take();
2967
2968 // Make sure the expression type is an ObjC pointer or "void *".
2969 QualType type = operand->getType();
2970 if (!type->isDependentType() &&
2971 !type->isObjCObjectPointerType()) {
2972 const PointerType *pointerType = type->getAs<PointerType>();
2973 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2974 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2975 << type << operand->getSourceRange();
2976 }
2977
2978 // The operand to @synchronized is a full-expression.
2979 return MaybeCreateExprWithCleanups(operand);
2980}
2981
John McCall60d7b3a2010-08-24 06:29:42 +00002982StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002983Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2984 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002985 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002986 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002987 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002988}
Sebastian Redl4b07b292008-12-22 19:15:10 +00002989
2990/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2991/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00002992StmtResult
John McCalld226f652010-08-21 09:40:31 +00002993Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00002994 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002995 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002996 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00002997 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00002998 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00002999}
Sebastian Redl8351da02008-12-22 21:35:02 +00003000
John McCallf85e1932011-06-15 23:02:42 +00003001StmtResult
3002Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3003 getCurFunction()->setHasBranchProtectedScope();
3004 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3005}
3006
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003007namespace {
3008
Sebastian Redlc447aba2009-07-29 17:15:45 +00003009class TypeWithHandler {
3010 QualType t;
3011 CXXCatchStmt *stmt;
3012public:
3013 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3014 : t(type), stmt(statement) {}
3015
John McCall0953e762009-09-24 19:53:00 +00003016 // An arbitrary order is fine as long as it places identical
3017 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00003018 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00003019 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003020 return true;
John McCall0953e762009-09-24 19:53:00 +00003021 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003022 return false;
3023 else
3024 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Sebastian Redlc447aba2009-07-29 17:15:45 +00003027 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00003028 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00003029 }
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Sebastian Redlc447aba2009-07-29 17:15:45 +00003031 CXXCatchStmt *getCatchStmt() const { return stmt; }
3032 SourceLocation getTypeSpecStartLoc() const {
3033 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3034 }
3035};
3036
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003037}
3038
Sebastian Redl8351da02008-12-22 21:35:02 +00003039/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3040/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003041StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00003042Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00003043 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00003044 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003045 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00003046 !getSourceManager().isInSystemHeader(TryLoc))
3047 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00003048
Sebastian Redl8351da02008-12-22 21:35:02 +00003049 unsigned NumHandlers = RawHandlers.size();
3050 assert(NumHandlers > 0 &&
3051 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00003052 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00003053
Chris Lattner5f9e2722011-07-23 10:55:15 +00003054 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00003055
3056 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003057 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00003058 if (!Handler->getExceptionDecl()) {
3059 if (i < NumHandlers - 1)
3060 return StmtError(Diag(Handler->getLocStart(),
3061 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00003062
Sebastian Redlc447aba2009-07-29 17:15:45 +00003063 continue;
3064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Sebastian Redlc447aba2009-07-29 17:15:45 +00003066 const QualType CaughtType = Handler->getCaughtType();
3067 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3068 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00003069 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00003070
3071 // Detect handlers for the same type as an earlier one.
3072 if (NumHandlers > 1) {
3073 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Sebastian Redlc447aba2009-07-29 17:15:45 +00003075 TypeWithHandler prev = TypesWithHandlers[0];
3076 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3077 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Sebastian Redlc447aba2009-07-29 17:15:45 +00003079 if (curr == prev) {
3080 Diag(curr.getTypeSpecStartLoc(),
3081 diag::warn_exception_caught_by_earlier_handler)
3082 << curr.getCatchStmt()->getCaughtType().getAsString();
3083 Diag(prev.getTypeSpecStartLoc(),
3084 diag::note_previous_exception_handler)
3085 << prev.getCatchStmt()->getCaughtType().getAsString();
3086 }
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Sebastian Redlc447aba2009-07-29 17:15:45 +00003088 prev = curr;
3089 }
3090 }
Mike Stump1eb44332009-09-09 15:08:12 +00003091
John McCall781472f2010-08-25 08:40:02 +00003092 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00003093
Sebastian Redl8351da02008-12-22 21:35:02 +00003094 // FIXME: We should detect handlers that cannot catch anything because an
3095 // earlier handler catches a superclass. Need to find a method that is not
3096 // quadratic for this.
3097 // Neither of these are explicitly forbidden, but every compiler detects them
3098 // and warns.
3099
John McCall9ae2f072010-08-23 23:25:46 +00003100 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00003101 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00003102}
John Wiegley28bbe4b2011-04-28 01:08:34 +00003103
3104StmtResult
3105Sema::ActOnSEHTryBlock(bool IsCXXTry,
3106 SourceLocation TryLoc,
3107 Stmt *TryBlock,
3108 Stmt *Handler) {
3109 assert(TryBlock && Handler);
3110
3111 getCurFunction()->setHasBranchProtectedScope();
3112
3113 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3114}
3115
3116StmtResult
3117Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3118 Expr *FilterExpr,
3119 Stmt *Block) {
3120 assert(FilterExpr && Block);
3121
3122 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00003123 return StmtError(Diag(FilterExpr->getExprLoc(),
3124 diag::err_filter_expression_integral)
3125 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00003126 }
3127
3128 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3129}
3130
3131StmtResult
3132Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3133 Stmt *Block) {
3134 assert(Block);
3135 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3136}
Douglas Gregorba0513d2011-10-25 01:33:02 +00003137
3138StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3139 bool IsIfExists,
3140 NestedNameSpecifierLoc QualifierLoc,
3141 DeclarationNameInfo NameInfo,
3142 Stmt *Nested)
3143{
3144 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3145 QualifierLoc, NameInfo,
3146 cast<CompoundStmt>(Nested));
3147}
3148
3149
3150StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3151 bool IsIfExists,
3152 CXXScopeSpec &SS,
3153 UnqualifiedId &Name,
3154 Stmt *Nested) {
3155 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3156 SS.getWithLocInContext(Context),
3157 GetNameFromUnqualifiedId(Name),
3158 Nested);
3159}