blob: 260001dabbe8076d978d177d35873d1a18d8546b [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"
Chad Rosierbe3d0db2012-08-09 17:33:11 +000035#include "llvm/Support/TargetSelect.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
John McCall60d7b3a2010-08-24 06:29:42 +000039StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCall9ae2f072010-08-23 23:25:46 +000040 Expr *E = expr.get();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000041 if (!E) // FIXME: FullExprArg has no error state?
42 return StmtError();
43
Chris Lattner834a72a2008-07-25 23:18:17 +000044 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
45 // void expression for its side effects. Conversion to void allows any
46 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000047
Chris Lattner834a72a2008-07-25 23:18:17 +000048 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000049 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
52
Argyrios Kyrtzidisb7d98d32011-04-27 05:04:02 +000053StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidise2ca8282011-09-01 21:53:45 +000054 bool HasLeadingEmptyMacro) {
55 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Reid Spencer5f016e22007-07-11 17:01:13 +000056}
57
Chris Lattner337e5502011-02-18 01:27:55 +000058StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
59 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000060 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner20401692009-04-12 20:13:14 +000062 // If we have an invalid decl, just return an error.
63 if (DG.isNull()) return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner24e1e702009-03-04 04:23:07 +000065 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000066}
67
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000068void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
69 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000070
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000071 // If we have an invalid decl, just return.
72 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCallf85e1932011-06-15 23:02:42 +000073 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
74
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000075 // suppress any potential 'unused variable' warning.
John McCallf85e1932011-06-15 23:02:42 +000076 var->setUsed();
77
John McCall7acddac2011-06-17 06:42:21 +000078 // foreach variables are never actually initialized in the way that
79 // the parser came up with.
80 var->setInit(0);
John McCallf85e1932011-06-15 23:02:42 +000081
John McCall7acddac2011-06-17 06:42:21 +000082 // In ARC, we don't need to retain the iteration variable of a fast
83 // enumeration loop. Rather than actually trying to catch that
84 // during declaration processing, we remove the consequences here.
David Blaikie4e4d0842012-03-11 07:00:24 +000085 if (getLangOpts().ObjCAutoRefCount) {
John McCall7acddac2011-06-17 06:42:21 +000086 QualType type = var->getType();
87
88 // Only do this if we inferred the lifetime. Inferred lifetime
89 // will show up as a local qualifier because explicit lifetime
90 // should have shown up as an AttributedType instead.
91 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
92 // Add 'const' and mark the variable as pseudo-strong.
93 var->setType(type.withConst());
94 var->setARCPseudoStrong(true);
John McCallf85e1932011-06-15 23:02:42 +000095 }
96 }
Fariborz Jahaniana7cf23a2009-11-19 22:12:37 +000097}
98
Chandler Carruthec8058f2011-08-17 09:34:37 +000099/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000100///
101/// Adding a cast to void (or other expression wrappers) will prevent the
102/// warning from firing.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000103static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000104 SourceLocation Loc;
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000105 bool IsNotEqual, CanAssign;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000106
107 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
108 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000109 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000110
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000111 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000112 IsNotEqual = Op->getOpcode() == BO_NE;
113 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000114 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
115 if (Op->getOperator() != OO_EqualEqual &&
116 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthec8058f2011-08-17 09:34:37 +0000117 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000118
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000119 Loc = Op->getOperatorLoc();
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000120 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
121 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000122 } else {
123 // Not a typo-prone comparison.
Chandler Carruthec8058f2011-08-17 09:34:37 +0000124 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000125 }
126
127 // Suppress warnings when the operator, suspicious as it may be, comes from
128 // a macro expansion.
129 if (Loc.isMacroID())
Chandler Carruthec8058f2011-08-17 09:34:37 +0000130 return false;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000131
Chandler Carruthec8058f2011-08-17 09:34:37 +0000132 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000133 << (unsigned)IsNotEqual << E->getSourceRange();
134
Chandler Carruth50bf68f2011-08-17 08:38:11 +0000135 // If the LHS is a plausible entity to assign to, provide a fixit hint to
136 // correct common typos.
137 if (CanAssign) {
138 if (IsNotEqual)
139 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
140 << FixItHint::CreateReplacement(Loc, "|=");
141 else
142 S.Diag(Loc, diag::note_equality_comparison_to_assign)
143 << FixItHint::CreateReplacement(Loc, "=");
144 }
Chandler Carruthec8058f2011-08-17 09:34:37 +0000145
146 return true;
Chandler Carruth9d8eb3b2011-08-17 08:38:04 +0000147}
148
Anders Carlsson636463e2009-07-30 22:17:18 +0000149void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +0000150 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
151 return DiagnoseUnusedExprResult(Label->getSubStmt());
152
Anders Carlsson75443112009-07-30 22:39:03 +0000153 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +0000154 if (!E)
155 return;
156
Eli Friedmana6115062012-05-24 00:47:05 +0000157 const Expr *WarnExpr;
Anders Carlsson636463e2009-07-30 22:17:18 +0000158 SourceLocation Loc;
159 SourceRange R1, R2;
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +0000160 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmana6115062012-05-24 00:47:05 +0000161 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson636463e2009-07-30 22:17:18 +0000162 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattner419cfb32009-08-16 16:57:27 +0000164 // Okay, we have an unused result. Depending on what the base expression is,
165 // we might want to make a more specific diagnostic. Check for one of these
166 // cases now.
167 unsigned DiagID = diag::warn_unused_expr;
John McCall4765fa02010-12-06 08:20:24 +0000168 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor4dffad62010-02-11 22:55:30 +0000169 E = Temps->getSubExpr();
Chandler Carruth34d49472011-02-21 00:56:56 +0000170 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
171 E = TempExpr->getSubExpr();
John McCall12f78a62010-12-02 01:19:52 +0000172
Chandler Carruthec8058f2011-08-17 09:34:37 +0000173 if (DiagnoseUnusedComparison(*this, E))
174 return;
175
Eli Friedmana6115062012-05-24 00:47:05 +0000176 E = WarnExpr;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000177 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCall0faede62010-03-12 07:11:26 +0000178 if (E->getType()->isVoidType())
179 return;
180
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000181 // If the callee has attribute pure, const, or warn_unused_result, warn with
182 // a more specific message to make it clear what is happening.
Nuno Lopesd20254f2009-12-20 23:11:08 +0000183 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000184 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000185 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +0000186 return;
187 }
188 if (FD->getAttr<PureAttr>()) {
189 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
190 return;
191 }
192 if (FD->getAttr<ConstAttr>()) {
193 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
194 return;
195 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000196 }
John McCall12f78a62010-12-02 01:19:52 +0000197 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000198 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCallf85e1932011-06-15 23:02:42 +0000199 Diag(Loc, diag::err_arc_unused_init_message) << R1;
200 return;
201 }
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000202 const ObjCMethodDecl *MD = ME->getMethodDecl();
203 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gay42d7b2d2011-08-04 23:11:04 +0000204 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000205 return;
206 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000207 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
208 const Expr *Source = POE->getSyntacticForm();
209 if (isa<ObjCSubscriptRefExpr>(Source))
210 DiagID = diag::warn_unused_container_subscript_expr;
211 else
212 DiagID = diag::warn_unused_property_expr;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000213 } else if (const CXXFunctionalCastExpr *FC
214 = dyn_cast<CXXFunctionalCastExpr>(E)) {
215 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
216 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
217 return;
Fariborz Jahanianf0317742010-03-30 18:22:15 +0000218 }
John McCall209acbd2010-04-06 22:24:14 +0000219 // Diagnose "(void*) blah" as a typo for "(void) blah".
220 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
221 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
222 QualType T = TI->getType();
223
224 // We really do want to use the non-canonical type here.
225 if (T == Context.VoidPtrTy) {
226 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
227
228 Diag(Loc, diag::warn_unused_voidptr)
229 << FixItHint::CreateRemoval(TL.getStarLoc());
230 return;
231 }
232 }
233
Eli Friedmana6115062012-05-24 00:47:05 +0000234 if (E->isGLValue() && E->getType().isVolatileQualified()) {
235 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
236 return;
237 }
238
Ted Kremenek351ba912011-02-23 01:52:04 +0000239 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson636463e2009-07-30 22:17:18 +0000240}
241
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000242void Sema::ActOnStartOfCompoundStmt() {
243 PushCompoundScope();
244}
245
246void Sema::ActOnFinishOfCompoundStmt() {
247 PopCompoundScope();
248}
249
250sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
251 return getCurFunction()->CompoundScopes.back();
252}
253
John McCall60d7b3a2010-08-24 06:29:42 +0000254StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000255Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +0000256 MultiStmtArg elts, bool isStmtExpr) {
257 unsigned NumElts = elts.size();
258 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000259 // If we're in C89 mode, check that we don't have any decls after stmts. If
260 // so, emit an extension diagnostic.
David Blaikie4e4d0842012-03-11 07:00:24 +0000261 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000262 // Note that __extension__ can be around a decl.
263 unsigned i = 0;
264 // Skip over all declarations.
265 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
266 /*empty*/;
267
268 // We found the end of the list or a statement. Scan for another declstmt.
269 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
270 /*empty*/;
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000272 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000273 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +0000274 Diag(D->getLocation(), diag::ext_mixed_decls_code);
275 }
276 }
Chris Lattner98414c12007-08-31 21:49:55 +0000277 // Warn about unused expressions in statements.
278 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000279 // Ignore statements that are last in a statement expression.
280 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000281 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Anders Carlsson636463e2009-07-30 22:17:18 +0000283 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000284 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000285
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000286 // Check for suspicious empty body (null statement) in `for' and `while'
287 // statements. Don't do anything for template instantiations, this just adds
288 // noise.
289 if (NumElts != 0 && !CurrentInstantiationScope &&
290 getCurCompoundScope().HasEmptyLoopBodies) {
291 for (unsigned i = 0; i != NumElts - 1; ++i)
292 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
293 }
294
Ted Kremenek8189cde2009-02-07 01:47:29 +0000295 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000296}
297
John McCall60d7b3a2010-08-24 06:29:42 +0000298StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000299Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
300 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner24e1e702009-03-04 04:23:07 +0000301 SourceLocation ColonLoc) {
John McCall9ae2f072010-08-23 23:25:46 +0000302 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl117054a2008-12-28 16:13:43 +0000303
John McCall781472f2010-08-25 08:40:02 +0000304 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000305 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000306 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000307 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000308
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (!getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000310 // C99 6.8.4.2p3: The expression shall be an integer constant.
311 // However, GCC allows any evaluatable integer expression.
Richard Smith282e7e62012-02-04 09:53:13 +0000312 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
313 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
314 if (!LHSVal)
315 return StmtError();
316 }
Richard Smith8ef7b202012-01-18 23:55:52 +0000317
318 // GCC extension: The expression shall be an integer constant.
319
Richard Smith282e7e62012-02-04 09:53:13 +0000320 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
321 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
322 // Recover from an error by just forgetting about it.
Richard Smith8ef7b202012-01-18 23:55:52 +0000323 }
324 }
325
Douglas Gregordbb26db2009-05-15 23:57:33 +0000326 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
327 ColonLoc);
John McCall781472f2010-08-25 08:40:02 +0000328 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000329 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000330}
331
Chris Lattner24e1e702009-03-04 04:23:07 +0000332/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCall9ae2f072010-08-23 23:25:46 +0000333void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000334 DiagnoseUnusedExprResult(SubStmt);
335
Chris Lattner24e1e702009-03-04 04:23:07 +0000336 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner24e1e702009-03-04 04:23:07 +0000337 CS->setSubStmt(SubStmt);
338}
339
John McCall60d7b3a2010-08-24 06:29:42 +0000340StmtResult
Mike Stump1eb44332009-09-09 15:08:12 +0000341Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000342 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth5440bfa2011-08-18 02:04:29 +0000343 DiagnoseUnusedExprResult(SubStmt);
344
John McCall781472f2010-08-25 08:40:02 +0000345 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000346 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000347 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000348 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000349
Douglas Gregordbb26db2009-05-15 23:57:33 +0000350 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCall781472f2010-08-25 08:40:02 +0000351 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000352 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353}
354
John McCall60d7b3a2010-08-24 06:29:42 +0000355StmtResult
Chris Lattner57ad3782011-02-17 20:34:02 +0000356Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
357 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000358 // If the label was multiply defined, reject it now.
359 if (TheDecl->getStmt()) {
360 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
361 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000362 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 }
Sebastian Redlde307472009-01-11 00:38:46 +0000364
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000365 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000366 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
367 TheDecl->setStmt(LS);
Abramo Bagnara203548b2011-03-03 18:24:14 +0000368 if (!TheDecl->isGnuLocal())
369 TheDecl->setLocation(IdentLoc);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000370 return Owned(LS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000371}
372
Richard Smith534986f2012-04-14 00:33:13 +0000373StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko49908902012-07-09 10:04:07 +0000374 ArrayRef<const Attr*> Attrs,
Richard Smith534986f2012-04-14 00:33:13 +0000375 Stmt *SubStmt) {
Alexander Kornienko49908902012-07-09 10:04:07 +0000376 // Fill in the declaration and return it.
377 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smith534986f2012-04-14 00:33:13 +0000378 return Owned(LS);
379}
380
John McCall60d7b3a2010-08-24 06:29:42 +0000381StmtResult
John McCalld226f652010-08-21 09:40:31 +0000382Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000383 Stmt *thenStmt, SourceLocation ElseLoc,
384 Stmt *elseStmt) {
John McCall60d7b3a2010-08-24 06:29:42 +0000385 ExprResult CondResult(CondVal.release());
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000387 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000388 if (CondVar) {
389 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +0000390 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000391 if (CondResult.isInvalid())
392 return StmtError();
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000393 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000394 Expr *ConditionExpr = CondResult.takeAs<Expr>();
395 if (!ConditionExpr)
396 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000397
Anders Carlsson75443112009-07-30 22:39:03 +0000398 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000399
John McCall9ae2f072010-08-23 23:25:46 +0000400 if (!elseStmt) {
Dmitri Gribenko625bb562012-02-14 22:14:32 +0000401 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
402 diag::warn_empty_if_body);
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000403 }
404
Anders Carlsson75443112009-07-30 22:39:03 +0000405 DiagnoseUnusedExprResult(elseStmt);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000407 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidis44aa1f32010-11-20 02:04:01 +0000408 thenStmt, ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000409}
410
Chris Lattnerf4021e72007-08-23 05:46:52 +0000411/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
412/// the specified width and sign. If an overflow occurs, detect it and emit
413/// the specified diagnostic.
414void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
415 unsigned NewWidth, bool NewSign,
Mike Stump1eb44332009-09-09 15:08:12 +0000416 SourceLocation Loc,
Chris Lattnerf4021e72007-08-23 05:46:52 +0000417 unsigned DiagID) {
418 // Perform a conversion to the promoted condition type if needed.
419 if (NewWidth > Val.getBitWidth()) {
420 // If this is an extension, just do it.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000421 Val = Val.extend(NewWidth);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000422 Val.setIsSigned(NewSign);
Douglas Gregorf9f627d2010-03-01 01:04:55 +0000423
424 // If the input was signed and negative and the output is
425 // unsigned, don't bother to warn: this is implementation-defined
426 // behavior.
427 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000428 } else if (NewWidth < Val.getBitWidth()) {
429 // If this is a truncation, check for overflow.
430 llvm::APSInt ConvVal(Val);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000431 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000432 ConvVal.setIsSigned(NewSign);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000433 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000434 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000435 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000436 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattnerf4021e72007-08-23 05:46:52 +0000438 // Regardless of whether a diagnostic was emitted, really do the
439 // truncation.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000440 Val = Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000441 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000442 } else if (NewSign != Val.isSigned()) {
443 // Convert the sign to match the sign of the condition. This can cause
444 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000445 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregor2853eac2010-02-18 00:56:01 +0000446 // behavior.
447 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerf4021e72007-08-23 05:46:52 +0000448 llvm::APSInt OldVal(Val);
449 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000450 }
451}
452
Chris Lattner0471f5b2007-08-23 18:29:20 +0000453namespace {
454 struct CaseCompareFunctor {
455 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
456 const llvm::APSInt &RHS) {
457 return LHS.first < RHS;
458 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000459 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
460 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
461 return LHS.first < RHS.first;
462 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000463 bool operator()(const llvm::APSInt &LHS,
464 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
465 return LHS < RHS.first;
466 }
467 };
468}
469
Chris Lattner764a7ce2007-09-21 18:15:22 +0000470/// CmpCaseVals - Comparison predicate for sorting case values.
471///
472static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
473 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
474 if (lhs.first < rhs.first)
475 return true;
476
477 if (lhs.first == rhs.first &&
478 lhs.second->getCaseLoc().getRawEncoding()
479 < rhs.second->getCaseLoc().getRawEncoding())
480 return true;
481 return false;
482}
483
Douglas Gregorba915af2010-02-08 22:24:16 +0000484/// CmpEnumVals - Comparison predicate for sorting enumeration values.
485///
486static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
487 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
488{
489 return lhs.first < rhs.first;
490}
491
492/// EqEnumVals - Comparison preficate for uniqing enumeration values.
493///
494static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
495 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
496{
497 return lhs.first == rhs.first;
498}
499
Chris Lattner5f048812009-10-16 16:45:22 +0000500/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
501/// potentially integral-promoted expression @p expr.
John McCalla8e0cd82011-08-06 07:30:58 +0000502static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
503 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
504 expr = cleanups->getSubExpr();
505 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
506 if (impcast->getCastKind() != CK_IntegralCast) break;
507 expr = impcast->getSubExpr();
Chris Lattner5f048812009-10-16 16:45:22 +0000508 }
509 return expr->getType();
510}
511
John McCall60d7b3a2010-08-24 06:29:42 +0000512StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000513Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCalld226f652010-08-21 09:40:31 +0000514 Decl *CondVar) {
John McCall60d7b3a2010-08-24 06:29:42 +0000515 ExprResult CondResult;
John McCall9ae2f072010-08-23 23:25:46 +0000516
Douglas Gregor586596f2010-05-06 17:25:47 +0000517 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +0000518 if (CondVar) {
519 ConditionVar = cast<VarDecl>(CondVar);
John McCall9ae2f072010-08-23 23:25:46 +0000520 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
521 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000522 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000523
John McCall9ae2f072010-08-23 23:25:46 +0000524 Cond = CondResult.release();
Douglas Gregor586596f2010-05-06 17:25:47 +0000525 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000526
John McCall9ae2f072010-08-23 23:25:46 +0000527 if (!Cond)
Douglas Gregor586596f2010-05-06 17:25:47 +0000528 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000529
Douglas Gregorab41fe92012-05-04 22:38:52 +0000530 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
531 Expr *Cond;
Chad Rosier8e1e0542012-06-20 18:51:04 +0000532
Douglas Gregorab41fe92012-05-04 22:38:52 +0000533 public:
534 SwitchConvertDiagnoser(Expr *Cond)
535 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000536
Douglas Gregorab41fe92012-05-04 22:38:52 +0000537 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
538 QualType T) {
539 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
540 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000541
Douglas Gregorab41fe92012-05-04 22:38:52 +0000542 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
543 QualType T) {
544 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
545 << T << Cond->getSourceRange();
546 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000547
Douglas Gregorab41fe92012-05-04 22:38:52 +0000548 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
549 QualType T,
550 QualType ConvTy) {
551 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
552 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000553
Douglas Gregorab41fe92012-05-04 22:38:52 +0000554 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
555 QualType ConvTy) {
556 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
557 << ConvTy->isEnumeralType() << ConvTy;
558 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000559
Douglas Gregorab41fe92012-05-04 22:38:52 +0000560 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
561 QualType T) {
562 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
563 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000564
Douglas Gregorab41fe92012-05-04 22:38:52 +0000565 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
566 QualType ConvTy) {
567 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
568 << ConvTy->isEnumeralType() << ConvTy;
569 }
Chad Rosier8e1e0542012-06-20 18:51:04 +0000570
Douglas Gregorab41fe92012-05-04 22:38:52 +0000571 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
572 QualType T,
573 QualType ConvTy) {
574 return DiagnosticBuilder::getEmpty();
575 }
576 } SwitchDiagnoser(Cond);
577
John McCall9ae2f072010-08-23 23:25:46 +0000578 CondResult
Douglas Gregorab41fe92012-05-04 22:38:52 +0000579 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +0000580 /*AllowScopedEnumerations*/ true);
John McCall9ae2f072010-08-23 23:25:46 +0000581 if (CondResult.isInvalid()) return StmtError();
582 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
John McCalla8e0cd82011-08-06 07:30:58 +0000584 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
585 CondResult = UsualUnaryConversions(Cond);
586 if (CondResult.isInvalid()) return StmtError();
587 Cond = CondResult.take();
588
John McCalld226f652010-08-21 09:40:31 +0000589 if (!CondVar) {
John McCallb4eb64d2010-10-08 02:01:28 +0000590 CheckImplicitConversions(Cond, SwitchLoc);
John McCall4765fa02010-12-06 08:20:24 +0000591 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +0000592 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +0000593 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +0000594 Cond = CondResult.take();
Douglas Gregor586596f2010-05-06 17:25:47 +0000595 }
John McCallb60a77e2010-08-01 00:26:45 +0000596
John McCall781472f2010-08-25 08:40:02 +0000597 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000598
John McCall9ae2f072010-08-23 23:25:46 +0000599 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCall781472f2010-08-25 08:40:02 +0000600 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregor586596f2010-05-06 17:25:47 +0000601 return Owned(SS);
Chris Lattner7e52de42010-01-24 01:50:29 +0000602}
603
Gabor Greif28164ab2010-10-01 22:05:14 +0000604static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
605 if (Val.getBitWidth() < BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000606 Val = Val.extend(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000607 else if (Val.getBitWidth() > BitWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +0000608 Val = Val.trunc(BitWidth);
Gabor Greif28164ab2010-10-01 22:05:14 +0000609 Val.setIsSigned(IsSigned);
610}
611
John McCall60d7b3a2010-08-24 06:29:42 +0000612StmtResult
John McCall9ae2f072010-08-23 23:25:46 +0000613Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
614 Stmt *BodyStmt) {
615 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCall781472f2010-08-25 08:40:02 +0000616 assert(SS == getCurFunction()->SwitchStack.back() &&
617 "switch stack missing push/pop!");
Sebastian Redlde307472009-01-11 00:38:46 +0000618
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000619 SS->setBody(BodyStmt, SwitchLoc);
John McCall781472f2010-08-25 08:40:02 +0000620 getCurFunction()->SwitchStack.pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000621
Chris Lattnerf4021e72007-08-23 05:46:52 +0000622 Expr *CondExpr = SS->getCond();
John McCalla8e0cd82011-08-06 07:30:58 +0000623 if (!CondExpr) return StmtError();
624
625 QualType CondType = CondExpr->getType();
626
John McCall0fb97082010-05-18 03:19:21 +0000627 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000628 QualType CondTypeBeforePromotion =
John McCalla8e0cd82011-08-06 07:30:58 +0000629 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregor84fb9c02009-11-23 13:46:08 +0000630
Chris Lattner5f048812009-10-16 16:45:22 +0000631 // C++ 6.4.2.p2:
632 // Integral promotions are performed (on the switch condition).
633 //
634 // A case value unrepresentable by the original switch condition
635 // type (before the promotion) doesn't make sense, even when it can
636 // be represented by the promoted type. Therefore we need to find
637 // the pre-promotion type of the switch condition.
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000638 if (!CondExpr->isTypeDependent()) {
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000639 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640 // type, when we started the switch statement. If we don't have an
Douglas Gregoracb0bd82010-06-29 23:25:20 +0000641 // appropriate type now, just return an error.
642 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000643 return StmtError();
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000644
Chris Lattner2b334bb2010-04-16 23:34:13 +0000645 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan12356b12009-10-17 19:32:54 +0000646 // switch(bool_expr) {...} is often a programmer error, e.g.
647 // switch(n && mask) { ... } // Doh - should be "n & mask".
648 // One can always use an if statement instead of switch(bool_expr).
649 Diag(SwitchLoc, diag::warn_bool_switch_condition)
650 << CondExpr->getSourceRange();
651 }
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000652 }
Sebastian Redlde307472009-01-11 00:38:46 +0000653
Chris Lattnerf4021e72007-08-23 05:46:52 +0000654 // Get the bitwidth of the switched-on value before promotions. We must
655 // convert the integer case values to this width before comparison.
Mike Stump1eb44332009-09-09 15:08:12 +0000656 bool HasDependentValue
Douglas Gregordbb26db2009-05-15 23:57:33 +0000657 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump1eb44332009-09-09 15:08:12 +0000658 unsigned CondWidth
Chris Lattner1d6ab7a2011-02-24 07:31:28 +0000659 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000660 bool CondIsSigned
661 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattnerf4021e72007-08-23 05:46:52 +0000663 // Accumulate all of the case values in a vector so that we can sort them
664 // and detect duplicates. This vector contains the APInt for the case after
665 // it has been converted to the condition type.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000666 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner0471f5b2007-08-23 18:29:20 +0000667 CaseValsTy CaseVals;
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Chris Lattnerf4021e72007-08-23 05:46:52 +0000669 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorba915af2010-02-08 22:24:16 +0000670 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
671 CaseRangesTy CaseRanges;
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerf4021e72007-08-23 05:46:52 +0000673 DefaultStmt *TheDefaultStmt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000675 bool CaseListIsErroneous = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Douglas Gregordbb26db2009-05-15 23:57:33 +0000677 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000678 SC = SC->getNextSwitchCase()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000680 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000681 if (TheDefaultStmt) {
682 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000683 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000684
Chris Lattnerf4021e72007-08-23 05:46:52 +0000685 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000686 // we'll return a valid AST. This requires recursing down the AST and
687 // finding it, not something we are set up to do right now. For now,
688 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000689 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000690 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000691 TheDefaultStmt = DS;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattnerf4021e72007-08-23 05:46:52 +0000693 } else {
694 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner1e0a3902008-01-16 19:17:22 +0000696 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000697
698 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
699 HasDependentValue = true;
700 break;
701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Richard Smith8ef7b202012-01-18 23:55:52 +0000703 llvm::APSInt LoVal;
Mike Stump1eb44332009-09-09 15:08:12 +0000704
David Blaikie4e4d0842012-03-11 07:00:24 +0000705 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000706 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
707 // constant expression of the promoted type of the switch condition.
708 ExprResult ConvLo =
709 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
710 if (ConvLo.isInvalid()) {
711 CaseListIsErroneous = true;
712 continue;
713 }
714 Lo = ConvLo.take();
715 } else {
716 // We already verified that the expression has a i-c-e value (C99
717 // 6.8.4.2p3) - get that value now.
718 LoVal = Lo->EvaluateKnownConstInt(Context);
719
720 // If the LHS is not the same type as the condition, insert an implicit
721 // cast.
722 Lo = DefaultLvalueConversion(Lo).take();
723 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
724 }
725
726 // Convert the value to the same width/sign as the condition had prior to
727 // integral promotions.
728 //
729 // FIXME: This causes us to reject valid code:
730 // switch ((char)c) { case 256: case 0: return 0; }
731 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerf4021e72007-08-23 05:46:52 +0000732 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000733 Lo->getLocStart(),
Chris Lattnerf4021e72007-08-23 05:46:52 +0000734 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000735
Chris Lattner1e0a3902008-01-16 19:17:22 +0000736 CS->setLHS(Lo);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000738 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000739 if (CS->getRHS()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000740 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregordbb26db2009-05-15 23:57:33 +0000741 CS->getRHS()->isValueDependent()) {
742 HasDependentValue = true;
743 break;
744 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000745 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump1eb44332009-09-09 15:08:12 +0000746 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000747 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000748 }
749 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000750
751 if (!HasDependentValue) {
John McCall0fb97082010-05-18 03:19:21 +0000752 // If we don't have a default statement, check whether the
753 // condition is constant.
754 llvm::APSInt ConstantCondValue;
755 bool HasConstantCond = false;
John McCall0fb97082010-05-18 03:19:21 +0000756 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith51f47082011-10-29 00:50:52 +0000757 HasConstantCond
Richard Smith80d4b552011-12-28 19:48:30 +0000758 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
759 Expr::SE_AllowSideEffects);
760 assert(!HasConstantCond ||
761 (ConstantCondValue.getBitWidth() == CondWidth &&
762 ConstantCondValue.isSigned() == CondIsSigned));
John McCall0fb97082010-05-18 03:19:21 +0000763 }
Richard Smith80d4b552011-12-28 19:48:30 +0000764 bool ShouldCheckConstantCond = HasConstantCond;
John McCall0fb97082010-05-18 03:19:21 +0000765
Douglas Gregordbb26db2009-05-15 23:57:33 +0000766 // Sort all the scalar case values so we can easily detect duplicates.
767 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
768
769 if (!CaseVals.empty()) {
John McCall0fb97082010-05-18 03:19:21 +0000770 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
771 if (ShouldCheckConstantCond &&
772 CaseVals[i].first == ConstantCondValue)
773 ShouldCheckConstantCond = false;
774
775 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000776 // If we have a duplicate, report it.
Douglas Gregor3940ce82012-05-16 05:32:58 +0000777 // First, determine if either case value has a name
778 StringRef PrevString, CurrString;
779 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
780 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
781 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
782 PrevString = DeclRef->getDecl()->getName();
783 }
784 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
785 CurrString = DeclRef->getDecl()->getName();
786 }
Douglas Gregor50de5e32012-05-16 16:11:17 +0000787 llvm::SmallString<16> CaseValStr;
788 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000789
790 if (PrevString == CurrString)
791 Diag(CaseVals[i].second->getLHS()->getLocStart(),
792 diag::err_duplicate_case) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000793 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor3940ce82012-05-16 05:32:58 +0000794 else
795 Diag(CaseVals[i].second->getLHS()->getLocStart(),
796 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor50de5e32012-05-16 16:11:17 +0000797 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
798 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor3940ce82012-05-16 05:32:58 +0000799 CaseValStr;
800
John McCall0fb97082010-05-18 03:19:21 +0000801 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000802 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000803 // FIXME: We really want to remove the bogus case stmt from the
804 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000805 CaseListIsErroneous = true;
806 }
807 }
808 }
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Douglas Gregordbb26db2009-05-15 23:57:33 +0000810 // Detect duplicate case ranges, which usually don't exist at all in
811 // the first place.
812 if (!CaseRanges.empty()) {
813 // Sort all the case ranges by their low value so we can easily detect
814 // overlaps between ranges.
815 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Douglas Gregordbb26db2009-05-15 23:57:33 +0000817 // Scan the ranges, computing the high values and removing empty ranges.
818 std::vector<llvm::APSInt> HiVals;
819 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCall0fb97082010-05-18 03:19:21 +0000820 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregordbb26db2009-05-15 23:57:33 +0000821 CaseStmt *CR = CaseRanges[i].second;
822 Expr *Hi = CR->getRHS();
Richard Smith8ef7b202012-01-18 23:55:52 +0000823 llvm::APSInt HiVal;
824
David Blaikie4e4d0842012-03-11 07:00:24 +0000825 if (getLangOpts().CPlusPlus0x) {
Richard Smith8ef7b202012-01-18 23:55:52 +0000826 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
827 // constant expression of the promoted type of the switch condition.
828 ExprResult ConvHi =
829 CheckConvertedConstantExpression(Hi, CondType, HiVal,
830 CCEK_CaseValue);
831 if (ConvHi.isInvalid()) {
832 CaseListIsErroneous = true;
833 continue;
834 }
835 Hi = ConvHi.take();
836 } else {
837 HiVal = Hi->EvaluateKnownConstInt(Context);
838
839 // If the RHS is not the same type as the condition, insert an
840 // implicit cast.
841 Hi = DefaultLvalueConversion(Hi).take();
842 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
843 }
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Douglas Gregordbb26db2009-05-15 23:57:33 +0000845 // Convert the value to the same width/sign as the condition.
846 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif28164ab2010-10-01 22:05:14 +0000847 Hi->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000848 diag::warn_case_value_overflow);
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregordbb26db2009-05-15 23:57:33 +0000850 CR->setRHS(Hi);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregordbb26db2009-05-15 23:57:33 +0000852 // If the low value is bigger than the high value, the case is empty.
John McCall0fb97082010-05-18 03:19:21 +0000853 if (LoVal > HiVal) {
Douglas Gregordbb26db2009-05-15 23:57:33 +0000854 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
855 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif28164ab2010-10-01 22:05:14 +0000856 Hi->getLocEnd());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000857 CaseRanges.erase(CaseRanges.begin()+i);
858 --i, --e;
859 continue;
860 }
John McCall0fb97082010-05-18 03:19:21 +0000861
862 if (ShouldCheckConstantCond &&
863 LoVal <= ConstantCondValue &&
864 ConstantCondValue <= HiVal)
865 ShouldCheckConstantCond = false;
866
Douglas Gregordbb26db2009-05-15 23:57:33 +0000867 HiVals.push_back(HiVal);
868 }
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregordbb26db2009-05-15 23:57:33 +0000870 // Rescan the ranges, looking for overlap with singleton values and other
871 // ranges. Since the range list is sorted, we only need to compare case
872 // ranges with their neighbors.
873 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
874 llvm::APSInt &CRLo = CaseRanges[i].first;
875 llvm::APSInt &CRHi = HiVals[i];
876 CaseStmt *CR = CaseRanges[i].second;
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Douglas Gregordbb26db2009-05-15 23:57:33 +0000878 // Check to see whether the case range overlaps with any
879 // singleton cases.
880 CaseStmt *OverlapStmt = 0;
881 llvm::APSInt OverlapVal(32);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregordbb26db2009-05-15 23:57:33 +0000883 // Find the smallest value >= the lower bound. If I is in the
884 // case range, then we have overlap.
885 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
886 CaseVals.end(), CRLo,
887 CaseCompareFunctor());
888 if (I != CaseVals.end() && I->first < CRHi) {
889 OverlapVal = I->first; // Found overlap with scalar.
890 OverlapStmt = I->second;
891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregordbb26db2009-05-15 23:57:33 +0000893 // Find the smallest value bigger than the upper bound.
894 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
895 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
896 OverlapVal = (I-1)->first; // Found overlap with scalar.
897 OverlapStmt = (I-1)->second;
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Douglas Gregordbb26db2009-05-15 23:57:33 +0000900 // Check to see if this case stmt overlaps with the subsequent
901 // case range.
902 if (i && CRLo <= HiVals[i-1]) {
903 OverlapVal = HiVals[i-1]; // Found overlap with range.
904 OverlapStmt = CaseRanges[i-1].second;
905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregordbb26db2009-05-15 23:57:33 +0000907 if (OverlapStmt) {
908 // If we have a duplicate, report it.
909 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
910 << OverlapVal.toString(10);
Mike Stump1eb44332009-09-09 15:08:12 +0000911 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregordbb26db2009-05-15 23:57:33 +0000912 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000913 // FIXME: We really want to remove the bogus case stmt from the
914 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000915 CaseListIsErroneous = true;
916 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000917 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000918 }
Douglas Gregorba915af2010-02-08 22:24:16 +0000919
John McCall0fb97082010-05-18 03:19:21 +0000920 // Complain if we have a constant condition and we didn't find a match.
921 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
922 // TODO: it would be nice if we printed enums as enums, chars as
923 // chars, etc.
924 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
925 << ConstantCondValue.toString(10)
926 << CondExpr->getSourceRange();
927 }
928
929 // Check to see if switch is over an Enum and handles all of its
Ted Kremenek559fb552010-09-09 00:05:53 +0000930 // values. We only issue a warning if there is not 'default:', but
931 // we still do the analysis to preserve this information in the AST
932 // (which can be used by flow-based analyes).
John McCall0fb97082010-05-18 03:19:21 +0000933 //
Chris Lattnerce784612010-09-16 17:09:42 +0000934 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenek559fb552010-09-09 00:05:53 +0000935
Douglas Gregorba915af2010-02-08 22:24:16 +0000936 // If switch has default case, then ignore it.
Ted Kremenek559fb552010-09-09 00:05:53 +0000937 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorba915af2010-02-08 22:24:16 +0000938 const EnumDecl *ED = ET->getDecl();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000939 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichet58f14c02011-06-02 00:47:27 +0000940 EnumValsTy;
Douglas Gregorba915af2010-02-08 22:24:16 +0000941 EnumValsTy EnumVals;
942
John McCall0fb97082010-05-18 03:19:21 +0000943 // Gather all enum values, set their type and sort them,
944 // allowing easier comparison with CaseVals.
945 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif28164ab2010-10-01 22:05:14 +0000946 EDI != ED->enumerator_end(); ++EDI) {
947 llvm::APSInt Val = EDI->getInitVal();
948 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie581deb32012-06-06 20:45:41 +0000949 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorba915af2010-02-08 22:24:16 +0000950 }
951 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCall0fb97082010-05-18 03:19:21 +0000952 EnumValsTy::iterator EIend =
953 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenek559fb552010-09-09 00:05:53 +0000954
955 // See which case values aren't in enum.
David Blaikie93667502012-01-22 02:31:55 +0000956 EnumValsTy::const_iterator EI = EnumVals.begin();
957 for (CaseValsTy::const_iterator CI = CaseVals.begin();
958 CI != CaseVals.end(); CI++) {
959 while (EI != EIend && EI->first < CI->first)
960 EI++;
961 if (EI == EIend || EI->first > CI->first)
962 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000963 << CondTypeBeforePromotion;
David Blaikie93667502012-01-22 02:31:55 +0000964 }
965 // See which of case ranges aren't in enum
966 EI = EnumVals.begin();
967 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
968 RI != CaseRanges.end() && EI != EIend; RI++) {
969 while (EI != EIend && EI->first < RI->first)
970 EI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971
David Blaikie93667502012-01-22 02:31:55 +0000972 if (EI == EIend || EI->first != RI->first) {
973 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000974 << CondTypeBeforePromotion;
Ted Kremenek47bb27f2010-09-09 06:53:59 +0000975 }
David Blaikie93667502012-01-22 02:31:55 +0000976
977 llvm::APSInt Hi =
978 RI->second->getRHS()->EvaluateKnownConstInt(Context);
979 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
980 while (EI != EIend && EI->first < Hi)
981 EI++;
982 if (EI == EIend || EI->first != Hi)
983 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahanian54faba42012-03-21 20:56:29 +0000984 << CondTypeBeforePromotion;
Douglas Gregorba915af2010-02-08 22:24:16 +0000985 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000986
Ted Kremenek559fb552010-09-09 00:05:53 +0000987 // Check which enum vals aren't in switch
Douglas Gregorba915af2010-02-08 22:24:16 +0000988 CaseValsTy::const_iterator CI = CaseVals.begin();
989 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenek559fb552010-09-09 00:05:53 +0000990 bool hasCasesNotInSwitch = false;
991
Chris Lattner5f9e2722011-07-23 10:55:15 +0000992 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000993
David Blaikie93667502012-01-22 02:31:55 +0000994 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattnerce784612010-09-16 17:09:42 +0000995 // Drop unneeded case values
Douglas Gregorba915af2010-02-08 22:24:16 +0000996 llvm::APSInt CIVal;
997 while (CI != CaseVals.end() && CI->first < EI->first)
998 CI++;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000999
Douglas Gregorba915af2010-02-08 22:24:16 +00001000 if (CI != CaseVals.end() && CI->first == EI->first)
1001 continue;
1002
Ted Kremenek559fb552010-09-09 00:05:53 +00001003 // Drop unneeded case ranges
Douglas Gregorba915af2010-02-08 22:24:16 +00001004 for (; RI != CaseRanges.end(); RI++) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001005 llvm::APSInt Hi =
1006 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif28164ab2010-10-01 22:05:14 +00001007 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorba915af2010-02-08 22:24:16 +00001008 if (EI->first <= Hi)
1009 break;
1010 }
1011
Ted Kremenek559fb552010-09-09 00:05:53 +00001012 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001013 hasCasesNotInSwitch = true;
David Blaikie31ceb612012-01-21 18:12:07 +00001014 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001015 }
Douglas Gregorba915af2010-02-08 22:24:16 +00001016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001017
David Blaikie585d7792012-01-23 04:46:12 +00001018 if (TheDefaultStmt && UnhandledNames.empty())
1019 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie31ceb612012-01-21 18:12:07 +00001020
Chris Lattnerce784612010-09-16 17:09:42 +00001021 // Produce a nice diagnostic if multiple values aren't handled.
1022 switch (UnhandledNames.size()) {
1023 case 0: break;
1024 case 1:
David Blaikie585d7792012-01-23 04:46:12 +00001025 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1026 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattnerce784612010-09-16 17:09:42 +00001027 << UnhandledNames[0];
1028 break;
1029 case 2:
David Blaikie585d7792012-01-23 04:46:12 +00001030 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1031 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattnerce784612010-09-16 17:09:42 +00001032 << UnhandledNames[0] << UnhandledNames[1];
1033 break;
1034 case 3:
David Blaikie585d7792012-01-23 04:46:12 +00001035 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1036 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattnerce784612010-09-16 17:09:42 +00001037 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1038 break;
1039 default:
David Blaikie585d7792012-01-23 04:46:12 +00001040 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1041 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattnerce784612010-09-16 17:09:42 +00001042 << (unsigned)UnhandledNames.size()
1043 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1044 break;
1045 }
Ted Kremenek559fb552010-09-09 00:05:53 +00001046
1047 if (!hasCasesNotInSwitch)
Ted Kremenek47bb27f2010-09-09 06:53:59 +00001048 SS->setAllEnumCasesCovered();
Douglas Gregorba915af2010-02-08 22:24:16 +00001049 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001050 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001051
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001052 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1053 diag::warn_empty_switch_body);
1054
Mike Stump390b4cc2009-05-16 07:39:55 +00001055 // FIXME: If the case list was broken is some way, we don't have a good system
1056 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +00001057 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +00001058 return StmtError();
1059
Sebastian Redlde307472009-01-11 00:38:46 +00001060 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001061}
1062
Fariborz Jahanian379b2812012-07-17 18:00:08 +00001063void
1064Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1065 Expr *SrcExpr) {
1066 unsigned DIAG = diag::warn_not_in_enum_assignement;
1067 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1068 == DiagnosticsEngine::Ignored)
1069 return;
1070
1071 if (const EnumType *ET = DstType->getAs<EnumType>())
1072 if (!Context.hasSameType(SrcType, DstType) &&
1073 SrcType->isIntegerType()) {
1074 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1075 SrcExpr->isIntegerConstantExpr(Context)) {
1076 // Get the bitwidth of the enum value before promotions.
1077 unsigned DstWith = Context.getIntWidth(DstType);
1078 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1079
1080 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1081 const EnumDecl *ED = ET->getDecl();
1082 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1083 EnumValsTy;
1084 EnumValsTy EnumVals;
1085
1086 // Gather all enum values, set their type and sort them,
1087 // allowing easier comparison with rhs constant.
1088 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1089 EDI != ED->enumerator_end(); ++EDI) {
1090 llvm::APSInt Val = EDI->getInitVal();
1091 AdjustAPSInt(Val, DstWith, DstIsSigned);
1092 EnumVals.push_back(std::make_pair(Val, *EDI));
1093 }
1094 if (EnumVals.empty())
1095 return;
1096 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1097 EnumValsTy::iterator EIend =
1098 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1099
1100 // See which case values aren't in enum.
1101 EnumValsTy::const_iterator EI = EnumVals.begin();
1102 while (EI != EIend && EI->first < RhsVal)
1103 EI++;
1104 if (EI == EIend || EI->first != RhsVal) {
1105 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1106 << DstType;
1107 }
1108 }
1109 }
1110}
1111
John McCall60d7b3a2010-08-24 06:29:42 +00001112StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001113Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCall9ae2f072010-08-23 23:25:46 +00001114 Decl *CondVar, Stmt *Body) {
John McCall60d7b3a2010-08-24 06:29:42 +00001115 ExprResult CondResult(Cond.release());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001116
Douglas Gregor5656e142009-11-24 21:15:44 +00001117 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001118 if (CondVar) {
1119 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001120 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001121 if (CondResult.isInvalid())
1122 return StmtError();
Douglas Gregor5656e142009-11-24 21:15:44 +00001123 }
John McCall9ae2f072010-08-23 23:25:46 +00001124 Expr *ConditionExpr = CondResult.take();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001125 if (!ConditionExpr)
1126 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001127
John McCall9ae2f072010-08-23 23:25:46 +00001128 DiagnoseUnusedExprResult(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001130 if (isa<NullStmt>(Body))
1131 getCurCompoundScope().setHasEmptyLoopBodies();
1132
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001133 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCall9ae2f072010-08-23 23:25:46 +00001134 Body, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001135}
1136
John McCall60d7b3a2010-08-24 06:29:42 +00001137StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00001138Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner98913592009-06-12 23:04:47 +00001139 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCall9ae2f072010-08-23 23:25:46 +00001140 Expr *Cond, SourceLocation CondRParen) {
1141 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +00001142
John Wiegley429bb272011-04-08 18:41:53 +00001143 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1144 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCall5a881bb2009-10-12 21:59:07 +00001145 return StmtError();
John Wiegley429bb272011-04-08 18:41:53 +00001146 Cond = CondResult.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
John McCallb4eb64d2010-10-08 02:01:28 +00001148 CheckImplicitConversions(Cond, DoLoc);
John Wiegley429bb272011-04-08 18:41:53 +00001149 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCall9ae2f072010-08-23 23:25:46 +00001150 if (CondResult.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001151 return StmtError();
John McCall9ae2f072010-08-23 23:25:46 +00001152 Cond = CondResult.take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001153
John McCall9ae2f072010-08-23 23:25:46 +00001154 DiagnoseUnusedExprResult(Body);
Anders Carlsson75443112009-07-30 22:39:03 +00001155
John McCall9ae2f072010-08-23 23:25:46 +00001156 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +00001157}
1158
Richard Trieu694e7962012-04-30 18:01:30 +00001159namespace {
1160 // This visitor will traverse a conditional statement and store all
1161 // the evaluated decls into a vector. Simple is set to true if none
1162 // of the excluded constructs are used.
1163 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1164 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1165 llvm::SmallVector<SourceRange, 10> &Ranges;
1166 bool Simple;
Richard Trieu694e7962012-04-30 18:01:30 +00001167public:
1168 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1169
1170 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerfacde172012-06-06 17:32:50 +00001171 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu694e7962012-04-30 18:01:30 +00001172 Inherited(S.Context),
1173 Decls(Decls),
1174 Ranges(Ranges),
Benjamin Kramerfacde172012-06-06 17:32:50 +00001175 Simple(true) {}
Richard Trieu694e7962012-04-30 18:01:30 +00001176
1177 bool isSimple() { return Simple; }
1178
1179 // Replaces the method in EvaluatedExprVisitor.
1180 void VisitMemberExpr(MemberExpr* E) {
1181 Simple = false;
1182 }
1183
1184 // Any Stmt not whitelisted will cause the condition to be marked complex.
1185 void VisitStmt(Stmt *S) {
1186 Simple = false;
1187 }
1188
1189 void VisitBinaryOperator(BinaryOperator *E) {
1190 Visit(E->getLHS());
1191 Visit(E->getRHS());
1192 }
1193
1194 void VisitCastExpr(CastExpr *E) {
1195 Visit(E->getSubExpr());
1196 }
1197
1198 void VisitUnaryOperator(UnaryOperator *E) {
1199 // Skip checking conditionals with derefernces.
1200 if (E->getOpcode() == UO_Deref)
1201 Simple = false;
1202 else
1203 Visit(E->getSubExpr());
1204 }
1205
1206 void VisitConditionalOperator(ConditionalOperator *E) {
1207 Visit(E->getCond());
1208 Visit(E->getTrueExpr());
1209 Visit(E->getFalseExpr());
1210 }
1211
1212 void VisitParenExpr(ParenExpr *E) {
1213 Visit(E->getSubExpr());
1214 }
1215
1216 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1217 Visit(E->getOpaqueValue()->getSourceExpr());
1218 Visit(E->getFalseExpr());
1219 }
1220
1221 void VisitIntegerLiteral(IntegerLiteral *E) { }
1222 void VisitFloatingLiteral(FloatingLiteral *E) { }
1223 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1224 void VisitCharacterLiteral(CharacterLiteral *E) { }
1225 void VisitGNUNullExpr(GNUNullExpr *E) { }
1226 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1227
1228 void VisitDeclRefExpr(DeclRefExpr *E) {
1229 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1230 if (!VD) return;
1231
1232 Ranges.push_back(E->getSourceRange());
1233
1234 Decls.insert(VD);
1235 }
1236
1237 }; // end class DeclExtractor
1238
1239 // DeclMatcher checks to see if the decls are used in a non-evauluated
1240 // context.
1241 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1242 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1243 bool FoundDecl;
Richard Trieu694e7962012-04-30 18:01:30 +00001244
1245public:
1246 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1247
1248 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1249 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1250 if (!Statement) return;
1251
1252 Visit(Statement);
1253 }
1254
1255 void VisitReturnStmt(ReturnStmt *S) {
1256 FoundDecl = true;
1257 }
1258
1259 void VisitBreakStmt(BreakStmt *S) {
1260 FoundDecl = true;
1261 }
1262
1263 void VisitGotoStmt(GotoStmt *S) {
1264 FoundDecl = true;
1265 }
1266
1267 void VisitCastExpr(CastExpr *E) {
1268 if (E->getCastKind() == CK_LValueToRValue)
1269 CheckLValueToRValueCast(E->getSubExpr());
1270 else
1271 Visit(E->getSubExpr());
1272 }
1273
1274 void CheckLValueToRValueCast(Expr *E) {
1275 E = E->IgnoreParenImpCasts();
1276
1277 if (isa<DeclRefExpr>(E)) {
1278 return;
1279 }
1280
1281 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1282 Visit(CO->getCond());
1283 CheckLValueToRValueCast(CO->getTrueExpr());
1284 CheckLValueToRValueCast(CO->getFalseExpr());
1285 return;
1286 }
1287
1288 if (BinaryConditionalOperator *BCO =
1289 dyn_cast<BinaryConditionalOperator>(E)) {
1290 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1291 CheckLValueToRValueCast(BCO->getFalseExpr());
1292 return;
1293 }
1294
1295 Visit(E);
1296 }
1297
1298 void VisitDeclRefExpr(DeclRefExpr *E) {
1299 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1300 if (Decls.count(VD))
1301 FoundDecl = true;
1302 }
1303
1304 bool FoundDeclInUse() { return FoundDecl; }
1305
1306 }; // end class DeclMatcher
1307
1308 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1309 Expr *Third, Stmt *Body) {
1310 // Condition is empty
1311 if (!Second) return;
1312
1313 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1314 Second->getLocStart())
1315 == DiagnosticsEngine::Ignored)
1316 return;
1317
1318 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1319 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1320 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerfacde172012-06-06 17:32:50 +00001321 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu694e7962012-04-30 18:01:30 +00001322 DE.Visit(Second);
1323
1324 // Don't analyze complex conditionals.
1325 if (!DE.isSimple()) return;
1326
1327 // No decls found.
1328 if (Decls.size() == 0) return;
1329
Richard Trieu90875992012-05-04 03:01:54 +00001330 // Don't warn on volatile, static, or global variables.
Richard Trieu694e7962012-04-30 18:01:30 +00001331 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1332 E = Decls.end();
1333 I != E; ++I)
Richard Trieu90875992012-05-04 03:01:54 +00001334 if ((*I)->getType().isVolatileQualified() ||
1335 (*I)->hasGlobalStorage()) return;
Richard Trieu694e7962012-04-30 18:01:30 +00001336
1337 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1338 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1339 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1340 return;
1341
1342 // Load decl names into diagnostic.
1343 if (Decls.size() > 4)
1344 PDiag << 0;
1345 else {
1346 PDiag << Decls.size();
1347 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1348 E = Decls.end();
1349 I != E; ++I)
1350 PDiag << (*I)->getDeclName();
1351 }
1352
1353 // Load SourceRanges into diagnostic if there is room.
1354 // Otherwise, load the SourceRange of the conditional expression.
1355 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1356 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1357 E = Ranges.end();
1358 I != E; ++I)
1359 PDiag << *I;
1360 else
1361 PDiag << Second->getSourceRange();
1362
1363 S.Diag(Ranges.begin()->getBegin(), PDiag);
1364 }
1365
1366} // end namespace
1367
John McCall60d7b3a2010-08-24 06:29:42 +00001368StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001369Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001370 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001371 FullExprArg third,
John McCall9ae2f072010-08-23 23:25:46 +00001372 SourceLocation RParenLoc, Stmt *Body) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001373 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001374 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001375 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1376 // declare identifiers for objects having storage class 'auto' or
1377 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001378 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1379 DI!=DE; ++DI) {
1380 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCallb6bbcc92010-10-15 04:57:14 +00001381 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001382 VD = 0;
1383 if (VD == 0)
1384 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1385 // FIXME: mark decl erroneous!
1386 }
Chris Lattnerae3b7012007-08-28 05:03:08 +00001387 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001389
Richard Trieu694e7962012-04-30 18:01:30 +00001390 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1391
John McCall60d7b3a2010-08-24 06:29:42 +00001392 ExprResult SecondResult(second.release());
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001393 VarDecl *ConditionVar = 0;
John McCalld226f652010-08-21 09:40:31 +00001394 if (secondVar) {
1395 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregor586596f2010-05-06 17:25:47 +00001396 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001397 if (SecondResult.isInvalid())
1398 return StmtError();
1399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001400
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001401 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
Anders Carlsson3af708f2009-08-01 01:39:59 +00001403 DiagnoseUnusedExprResult(First);
1404 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +00001405 DiagnoseUnusedExprResult(Body);
1406
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001407 if (isa<NullStmt>(Body))
1408 getCurCompoundScope().setHasEmptyLoopBodies();
1409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410 return Owned(new (Context) ForStmt(Context, First,
1411 SecondResult.take(), ConditionVar,
1412 Third, Body, ForLoc, LParenLoc,
Douglas Gregor43dec6b2010-06-21 23:44:13 +00001413 RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001414}
1415
John McCallf6a16482010-12-04 03:47:34 +00001416/// In an Objective C collection iteration statement:
1417/// for (x in y)
1418/// x can be an arbitrary l-value expression. Bind it up as a
1419/// full-expression.
1420StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCall29bbd1a2012-03-30 05:43:39 +00001421 // Reduce placeholder expressions here. Note that this rejects the
1422 // use of pseudo-object l-values in this position.
1423 ExprResult result = CheckPlaceholderExpr(E);
1424 if (result.isInvalid()) return StmtError();
1425 E = result.take();
1426
John McCallf6a16482010-12-04 03:47:34 +00001427 CheckImplicitConversions(E);
John McCall29bbd1a2012-03-30 05:43:39 +00001428
1429 result = MaybeCreateExprWithCleanups(E);
1430 if (result.isInvalid()) return StmtError();
1431
1432 return Owned(static_cast<Stmt*>(result.take()));
John McCallf6a16482010-12-04 03:47:34 +00001433}
1434
John McCall990567c2011-07-27 01:07:15 +00001435ExprResult
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001436Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1437 if (!collection)
1438 return ExprError();
1439
John McCall990567c2011-07-27 01:07:15 +00001440 // Bail out early if we've got a type-dependent expression.
1441 if (collection->isTypeDependent()) return Owned(collection);
1442
1443 // Perform normal l-value conversion.
1444 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1445 if (result.isInvalid())
1446 return ExprError();
1447 collection = result.take();
1448
1449 // The operand needs to have object-pointer type.
1450 // TODO: should we do a contextual conversion?
1451 const ObjCObjectPointerType *pointerType =
1452 collection->getType()->getAs<ObjCObjectPointerType>();
1453 if (!pointerType)
1454 return Diag(forLoc, diag::err_collection_expr_type)
1455 << collection->getType() << collection->getSourceRange();
1456
1457 // Check that the operand provides
1458 // - countByEnumeratingWithState:objects:count:
1459 const ObjCObjectType *objectType = pointerType->getObjectType();
1460 ObjCInterfaceDecl *iface = objectType->getInterface();
1461
1462 // If we have a forward-declared type, we can't do this check.
Douglas Gregorb3029962011-11-14 22:10:01 +00001463 // Under ARC, it is an error not to have a forward-declared class.
1464 if (iface &&
1465 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikie4e4d0842012-03-11 07:00:24 +00001466 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001467 ? diag::err_arc_collection_forward
1468 : 0,
1469 collection)) {
John McCall990567c2011-07-27 01:07:15 +00001470 // Otherwise, if we have any useful type information, check that
1471 // the type declares the appropriate method.
1472 } else if (iface || !objectType->qual_empty()) {
1473 IdentifierInfo *selectorIdents[] = {
1474 &Context.Idents.get("countByEnumeratingWithState"),
1475 &Context.Idents.get("objects"),
1476 &Context.Idents.get("count")
1477 };
1478 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1479
1480 ObjCMethodDecl *method = 0;
1481
1482 // If there's an interface, look in both the public and private APIs.
1483 if (iface) {
1484 method = iface->lookupInstanceMethod(selector);
Anna Zakse61354b2012-07-27 19:07:44 +00001485 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall990567c2011-07-27 01:07:15 +00001486 }
1487
1488 // Also check protocol qualifiers.
1489 if (!method)
1490 method = LookupMethodInQualifiedType(selector, pointerType,
1491 /*instance*/ true);
1492
1493 // If we didn't find it anywhere, give up.
1494 if (!method) {
1495 Diag(forLoc, diag::warn_collection_expr_type)
1496 << collection->getType() << selector << collection->getSourceRange();
1497 }
1498
1499 // TODO: check for an incompatible signature?
1500 }
1501
1502 // Wrap up any cleanups in the expression.
1503 return Owned(MaybeCreateExprWithCleanups(collection));
1504}
1505
John McCall60d7b3a2010-08-24 06:29:42 +00001506StmtResult
Sebastian Redlf05b1522009-01-16 23:28:06 +00001507Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1508 SourceLocation LParenLoc,
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001509 Stmt *First, Expr *collection,
1510 SourceLocation RParenLoc) {
1511
1512 ExprResult CollectionExprResult =
1513 CheckObjCForCollectionOperand(ForLoc, collection);
1514
Fariborz Jahanian20552d22008-01-10 20:33:58 +00001515 if (First) {
1516 QualType FirstType;
1517 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +00001518 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001519 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1520 diag::err_toomany_element_decls));
1521
John McCallf85e1932011-06-15 23:02:42 +00001522 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1523 FirstType = D->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001524 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1525 // declare identifiers for objects having storage class 'auto' or
1526 // 'register'.
John McCallf85e1932011-06-15 23:02:42 +00001527 if (!D->hasLocalStorage())
1528 return StmtError(Diag(D->getLocation(),
Sebastian Redlf05b1522009-01-16 23:28:06 +00001529 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001530 } else {
Douglas Gregorc3203e72010-04-22 23:10:45 +00001531 Expr *FirstE = cast<Expr>(First);
John McCall7eb0a9e2010-11-24 05:12:34 +00001532 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlf05b1522009-01-16 23:28:06 +00001533 return StmtError(Diag(First->getLocStart(),
1534 diag::err_selector_element_not_lvalue)
1535 << First->getSourceRange());
1536
Mike Stump1eb44332009-09-09 15:08:12 +00001537 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +00001538 }
Douglas Gregorc3203e72010-04-22 23:10:45 +00001539 if (!FirstType->isDependentType() &&
1540 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +00001541 !FirstType->isBlockPointerType())
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001542 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1543 << FirstType << First->getSourceRange());
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001544 }
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001545
1546 if (CollectionExprResult.isInvalid())
1547 return StmtError();
1548
1549 return Owned(new (Context) ObjCForCollectionStmt(First,
1550 CollectionExprResult.take(), 0,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001551 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +00001552}
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
Richard Smithad762fc2011-04-14 22:09:26 +00001554namespace {
1555
1556enum BeginEndFunction {
1557 BEF_begin,
1558 BEF_end
1559};
1560
1561/// Build a variable declaration for a for-range statement.
1562static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1563 QualType Type, const char *Name) {
1564 DeclContext *DC = SemaRef.CurContext;
1565 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1566 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1567 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1568 TInfo, SC_Auto, SC_None);
Richard Smithb403d6d2011-04-18 15:49:25 +00001569 Decl->setImplicit();
Richard Smithad762fc2011-04-14 22:09:26 +00001570 return Decl;
1571}
1572
1573/// Finish building a variable declaration for a for-range statement.
1574/// \return true if an error occurs.
1575static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1576 SourceLocation Loc, int diag) {
1577 // Deduce the type for the iterator variable now rather than leaving it to
1578 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1579 TypeSourceInfo *InitTSI = 0;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00001580 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001581 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1582 Sema::DAR_Failed)
Richard Smithad762fc2011-04-14 22:09:26 +00001583 SemaRef.Diag(Loc, diag) << Init->getType();
1584 if (!InitTSI) {
1585 Decl->setInvalidDecl();
1586 return true;
1587 }
1588 Decl->setTypeSourceInfo(InitTSI);
1589 Decl->setType(InitTSI->getType());
1590
John McCallf85e1932011-06-15 23:02:42 +00001591 // In ARC, infer lifetime.
1592 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1593 // we're doing the equivalent of fast iteration.
David Blaikie4e4d0842012-03-11 07:00:24 +00001594 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001595 SemaRef.inferObjCARCLifetime(Decl))
1596 Decl->setInvalidDecl();
1597
Richard Smithad762fc2011-04-14 22:09:26 +00001598 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1599 /*TypeMayContainAuto=*/false);
1600 SemaRef.FinalizeDeclaration(Decl);
Richard Smithb403d6d2011-04-18 15:49:25 +00001601 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smithad762fc2011-04-14 22:09:26 +00001602 return false;
1603}
1604
1605/// Produce a note indicating which begin/end function was implicitly called
1606/// by a C++0x for-range statement. This is often not obvious from the code,
1607/// nor from the diagnostics produced when analysing the implicit expressions
1608/// required in a for-range statement.
1609void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1610 BeginEndFunction BEF) {
1611 CallExpr *CE = dyn_cast<CallExpr>(E);
1612 if (!CE)
1613 return;
1614 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1615 if (!D)
1616 return;
1617 SourceLocation Loc = D->getLocation();
1618
1619 std::string Description;
1620 bool IsTemplate = false;
1621 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1622 Description = SemaRef.getTemplateArgumentBindingsText(
1623 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1624 IsTemplate = true;
1625 }
1626
1627 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1628 << BEF << IsTemplate << Description << E->getType();
1629}
1630
1631/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1632/// given LookupResult is non-empty, it is assumed to describe a member which
1633/// will be invoked. Otherwise, the function will be found via argument
1634/// dependent lookup.
1635static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1636 SourceLocation Loc,
1637 VarDecl *Decl,
1638 BeginEndFunction BEF,
1639 const DeclarationNameInfo &NameInfo,
1640 LookupResult &MemberLookup,
1641 Expr *Range) {
1642 ExprResult CallExpr;
1643 if (!MemberLookup.empty()) {
1644 ExprResult MemberRef =
1645 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1646 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001647 /*TemplateKWLoc=*/SourceLocation(),
1648 /*FirstQualifierInScope=*/0,
1649 MemberLookup,
Richard Smithad762fc2011-04-14 22:09:26 +00001650 /*TemplateArgs=*/0);
1651 if (MemberRef.isInvalid())
1652 return ExprError();
1653 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1654 Loc, 0);
1655 if (CallExpr.isInvalid())
1656 return ExprError();
1657 } else {
1658 UnresolvedSet<0> FoundNames;
1659 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1660 // std is an associated namespace.
1661 UnresolvedLookupExpr *Fn =
1662 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1663 NestedNameSpecifierLoc(), NameInfo,
1664 /*NeedsADL=*/true, /*Overloaded=*/false,
1665 FoundNames.begin(), FoundNames.end(),
1666 /*LookInStdNamespace=*/true);
1667 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00001668 0, /*AllowTypoCorrection=*/false);
Richard Smithad762fc2011-04-14 22:09:26 +00001669 if (CallExpr.isInvalid()) {
1670 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1671 << Range->getType();
1672 return ExprError();
1673 }
1674 }
1675 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1676 diag::err_for_range_iter_deduction_failure)) {
1677 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1678 return ExprError();
1679 }
1680 return CallExpr;
1681}
1682
1683}
1684
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001685static bool ObjCEnumerationCollection(Expr *Collection) {
1686 return !Collection->isTypeDependent()
1687 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1688}
1689
Richard Smithad762fc2011-04-14 22:09:26 +00001690/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1691///
1692/// C++0x [stmt.ranged]:
1693/// A range-based for statement is equivalent to
1694///
1695/// {
1696/// auto && __range = range-init;
1697/// for ( auto __begin = begin-expr,
1698/// __end = end-expr;
1699/// __begin != __end;
1700/// ++__begin ) {
1701/// for-range-declaration = *__begin;
1702/// statement
1703/// }
1704/// }
1705///
1706/// The body of the loop is not available yet, since it cannot be analysed until
1707/// we have determined the type of the for-range-declaration.
1708StmtResult
1709Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1710 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1711 SourceLocation RParenLoc) {
1712 if (!First || !Range)
1713 return StmtError();
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001714
1715 if (ObjCEnumerationCollection(Range))
1716 return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1717 RParenLoc);
Richard Smithad762fc2011-04-14 22:09:26 +00001718
1719 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1720 assert(DS && "first part of for range not a decl stmt");
1721
1722 if (!DS->isSingleDecl()) {
1723 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1724 return StmtError();
1725 }
1726 if (DS->getSingleDecl()->isInvalidDecl())
1727 return StmtError();
1728
1729 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1730 return StmtError();
1731
1732 // Build auto && __range = range-init
1733 SourceLocation RangeLoc = Range->getLocStart();
1734 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1735 Context.getAutoRRefDeductType(),
1736 "__range");
1737 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1738 diag::err_for_range_deduction_failure))
1739 return StmtError();
1740
1741 // Claim the type doesn't contain auto: we've already done the checking.
1742 DeclGroupPtrTy RangeGroup =
1743 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1744 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1745 if (RangeDecl.isInvalid())
1746 return StmtError();
1747
1748 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1749 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1750 RParenLoc);
1751}
1752
1753/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1754StmtResult
1755Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1756 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1757 Expr *Inc, Stmt *LoopVarDecl,
1758 SourceLocation RParenLoc) {
1759 Scope *S = getCurScope();
1760
1761 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1762 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1763 QualType RangeVarType = RangeVar->getType();
1764
1765 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1766 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1767
1768 StmtResult BeginEndDecl = BeginEnd;
1769 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1770
1771 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1772 SourceLocation RangeLoc = RangeVar->getLocation();
1773
Ted Kremeneke50b0152011-10-10 22:36:28 +00001774 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1775
1776 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1777 VK_LValue, ColonLoc);
1778 if (BeginRangeRef.isInvalid())
1779 return StmtError();
1780
1781 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1782 VK_LValue, ColonLoc);
1783 if (EndRangeRef.isInvalid())
Richard Smithad762fc2011-04-14 22:09:26 +00001784 return StmtError();
1785
1786 QualType AutoType = Context.getAutoDeductType();
1787 Expr *Range = RangeVar->getInit();
1788 if (!Range)
1789 return StmtError();
1790 QualType RangeType = Range->getType();
1791
1792 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001793 diag::err_for_range_incomplete_type))
Richard Smithad762fc2011-04-14 22:09:26 +00001794 return StmtError();
1795
1796 // Build auto __begin = begin-expr, __end = end-expr.
1797 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1798 "__begin");
1799 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1800 "__end");
1801
1802 // Build begin-expr and end-expr and attach to __begin and __end variables.
1803 ExprResult BeginExpr, EndExpr;
1804 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1805 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1806 // __range + __bound, respectively, where __bound is the array bound. If
1807 // _RangeT is an array of unknown size or an array of incomplete type,
1808 // the program is ill-formed;
1809
1810 // begin-expr is __range.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001811 BeginExpr = BeginRangeRef;
1812 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smithad762fc2011-04-14 22:09:26 +00001813 diag::err_for_range_iter_deduction_failure)) {
1814 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1815 return StmtError();
1816 }
1817
1818 // Find the array bound.
1819 ExprResult BoundExpr;
1820 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1821 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu1dd986d2011-05-02 23:00:27 +00001822 Context.getPointerDiffType(),
1823 RangeLoc));
Richard Smithad762fc2011-04-14 22:09:26 +00001824 else if (const VariableArrayType *VAT =
1825 dyn_cast<VariableArrayType>(UnqAT))
1826 BoundExpr = VAT->getSizeExpr();
1827 else {
1828 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1829 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikieb219cfc2011-09-23 05:06:16 +00001830 llvm_unreachable("Unexpected array type in for-range");
Richard Smithad762fc2011-04-14 22:09:26 +00001831 }
1832
1833 // end-expr is __range + __bound.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001834 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smithad762fc2011-04-14 22:09:26 +00001835 BoundExpr.get());
1836 if (EndExpr.isInvalid())
1837 return StmtError();
1838 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1839 diag::err_for_range_iter_deduction_failure)) {
1840 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1841 return StmtError();
1842 }
1843 } else {
1844 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1845 ColonLoc);
1846 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1847 ColonLoc);
1848
1849 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1850 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1851
1852 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1853 // - if _RangeT is a class type, the unqualified-ids begin and end are
1854 // looked up in the scope of class _RangeT as if by class member access
1855 // lookup (3.4.5), and if either (or both) finds at least one
1856 // declaration, begin-expr and end-expr are __range.begin() and
1857 // __range.end(), respectively;
1858 LookupQualifiedName(BeginMemberLookup, D);
1859 LookupQualifiedName(EndMemberLookup, D);
1860
1861 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1862 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1863 << RangeType << BeginMemberLookup.empty();
1864 return StmtError();
1865 }
1866 } else {
1867 // - otherwise, begin-expr and end-expr are begin(__range) and
1868 // end(__range), respectively, where begin and end are looked up with
1869 // argument-dependent lookup (3.4.2). For the purposes of this name
1870 // lookup, namespace std is an associated namespace.
1871 }
1872
1873 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1874 BEF_begin, BeginNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001875 BeginMemberLookup,
1876 BeginRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001877 if (BeginExpr.isInvalid())
1878 return StmtError();
1879
1880 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1881 BEF_end, EndNameInfo,
Ted Kremeneke50b0152011-10-10 22:36:28 +00001882 EndMemberLookup, EndRangeRef.get());
Richard Smithad762fc2011-04-14 22:09:26 +00001883 if (EndExpr.isInvalid())
1884 return StmtError();
1885 }
1886
1887 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1888 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1889 if (!Context.hasSameType(BeginType, EndType)) {
1890 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1891 << BeginType << EndType;
1892 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1893 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1894 }
1895
1896 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1897 // Claim the type doesn't contain auto: we've already done the checking.
1898 DeclGroupPtrTy BeginEndGroup =
1899 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1900 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1901
Ted Kremeneke50b0152011-10-10 22:36:28 +00001902 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1903 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smithad762fc2011-04-14 22:09:26 +00001904 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001905 if (BeginRef.isInvalid())
1906 return StmtError();
1907
Richard Smithad762fc2011-04-14 22:09:26 +00001908 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1909 VK_LValue, ColonLoc);
Ted Kremeneke50b0152011-10-10 22:36:28 +00001910 if (EndRef.isInvalid())
1911 return StmtError();
Richard Smithad762fc2011-04-14 22:09:26 +00001912
1913 // Build and check __begin != __end expression.
1914 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1915 BeginRef.get(), EndRef.get());
1916 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1917 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1918 if (NotEqExpr.isInvalid()) {
1919 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1920 if (!Context.hasSameType(BeginType, EndType))
1921 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1922 return StmtError();
1923 }
1924
1925 // Build and check ++__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001926 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1927 VK_LValue, ColonLoc);
1928 if (BeginRef.isInvalid())
1929 return StmtError();
1930
Richard Smithad762fc2011-04-14 22:09:26 +00001931 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1932 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1933 if (IncrExpr.isInvalid()) {
1934 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1935 return StmtError();
1936 }
1937
1938 // Build and check *__begin expression.
Ted Kremeneke50b0152011-10-10 22:36:28 +00001939 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1940 VK_LValue, ColonLoc);
1941 if (BeginRef.isInvalid())
1942 return StmtError();
1943
Richard Smithad762fc2011-04-14 22:09:26 +00001944 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1945 if (DerefExpr.isInvalid()) {
1946 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1947 return StmtError();
1948 }
1949
1950 // Attach *__begin as initializer for VD.
1951 if (!LoopVar->isInvalidDecl()) {
1952 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1953 /*TypeMayContainAuto=*/true);
1954 if (LoopVar->isInvalidDecl())
1955 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1956 }
Richard Smithcd6f3662011-06-21 23:07:19 +00001957 } else {
1958 // The range is implicitly used as a placeholder when it is dependent.
1959 RangeVar->setUsed();
Richard Smithad762fc2011-04-14 22:09:26 +00001960 }
1961
1962 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1963 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1964 NotEqExpr.take(), IncrExpr.take(),
1965 LoopVarDS, /*Body=*/0, ForLoc,
1966 ColonLoc, RParenLoc));
1967}
1968
Fariborz Jahaniana1eec4b2012-07-03 22:00:52 +00001969/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1970/// statement.
1971StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1972 if (!S || !B)
1973 return StmtError();
1974 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1975
1976 ForStmt->setBody(B);
1977 return S;
1978}
1979
Richard Smithad762fc2011-04-14 22:09:26 +00001980/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1981/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1982/// body cannot be performed until after the type of the range variable is
1983/// determined.
1984StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1985 if (!S || !B)
1986 return StmtError();
1987
Fariborz Jahanian4d3db4e2012-07-06 19:04:04 +00001988 if (isa<ObjCForCollectionStmt>(S))
1989 return FinishObjCForCollectionStmt(S, B);
1990
Dmitri Gribenko625bb562012-02-14 22:14:32 +00001991 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1992 ForStmt->setBody(B);
1993
1994 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1995 diag::warn_empty_range_based_for_body);
1996
Richard Smithad762fc2011-04-14 22:09:26 +00001997 return S;
1998}
1999
Chris Lattner57ad3782011-02-17 20:34:02 +00002000StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2001 SourceLocation LabelLoc,
2002 LabelDecl *TheDecl) {
2003 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002004 TheDecl->setUsed();
2005 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002006}
2007
John McCall60d7b3a2010-08-24 06:29:42 +00002008StmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +00002009Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002010 Expr *E) {
Eli Friedmanbbf46232009-03-26 00:18:06 +00002011 // Convert operand to void*
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002012 if (!E->isTypeDependent()) {
2013 QualType ETy = E->getType();
Chandler Carruth28779982010-01-31 10:26:25 +00002014 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley429bb272011-04-08 18:41:53 +00002015 ExprResult ExprRes = Owned(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002016 AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002017 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2018 if (ExprRes.isInvalid())
2019 return StmtError();
2020 E = ExprRes.take();
Chandler Carruth28779982010-01-31 10:26:25 +00002021 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002022 return StmtError();
Eli Friedmand29975f2012-01-31 22:47:07 +00002023 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002024 }
John McCallb60a77e2010-08-01 00:26:45 +00002025
John McCall781472f2010-08-25 08:40:02 +00002026 getCurFunction()->setHasIndirectGoto();
John McCallb60a77e2010-08-01 00:26:45 +00002027
Douglas Gregor5f1b9e62009-05-16 00:20:29 +00002028 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002029}
2030
John McCall60d7b3a2010-08-24 06:29:42 +00002031StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002032Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 Scope *S = CurScope->getContinueParent();
2034 if (!S) {
2035 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002036 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002038
Ted Kremenek8189cde2009-02-07 01:47:29 +00002039 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002040}
2041
John McCall60d7b3a2010-08-24 06:29:42 +00002042StmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +00002043Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 Scope *S = CurScope->getBreakParent();
2045 if (!S) {
2046 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002047 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002049
Ted Kremenek8189cde2009-02-07 01:47:29 +00002050 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002051}
2052
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053/// \brief Determine whether the given expression is a candidate for
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002054/// copy elision in either a return statement or a throw expression.
Douglas Gregor5077c382010-05-15 06:01:05 +00002055///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002056/// \param ReturnType If we're determining the copy elision candidate for
2057/// a return statement, this is the return type of the function. If we're
2058/// determining the copy elision candidate for a throw expression, this will
2059/// be a NULL type.
Douglas Gregor5077c382010-05-15 06:01:05 +00002060///
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002061/// \param E The expression being returned from the function or block, or
2062/// being thrown.
Douglas Gregor5077c382010-05-15 06:01:05 +00002063///
Douglas Gregor4926d832011-05-20 15:00:53 +00002064/// \param AllowFunctionParameter Whether we allow function parameters to
2065/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2066/// we re-use this logic to determine whether we should try to move as part of
2067/// a return or throw (which does allow function parameters).
Douglas Gregor5077c382010-05-15 06:01:05 +00002068///
2069/// \returns The NRVO candidate variable, if the return statement may use the
2070/// NRVO, or NULL if there is no such candidate.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002071const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2072 Expr *E,
2073 bool AllowFunctionParameter) {
2074 QualType ExprType = E->getType();
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002075 // - in a return statement in a function with ...
2076 // ... a class return type ...
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002077 if (!ReturnType.isNull()) {
2078 if (!ReturnType->isRecordType())
2079 return 0;
2080 // ... the same cv-unqualified type as the function return type ...
2081 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2082 return 0;
2083 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084
2085 // ... the expression is the name of a non-volatile automatic object
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002086 // (other than a function or catch-clause parameter)) ...
2087 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber89510672012-07-11 22:50:15 +00002088 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor5077c382010-05-15 06:01:05 +00002089 return 0;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002090 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2091 if (!VD)
Douglas Gregor5077c382010-05-15 06:01:05 +00002092 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002093
John McCall1cd76e82011-11-11 03:57:31 +00002094 // ...object (other than a function or catch-clause parameter)...
2095 if (VD->getKind() != Decl::Var &&
2096 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2097 return 0;
2098 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002099
John McCall1cd76e82011-11-11 03:57:31 +00002100 // ...automatic...
2101 if (!VD->hasLocalStorage()) return 0;
2102
2103 // ...non-volatile...
2104 if (VD->getType().isVolatileQualified()) return 0;
2105 if (VD->getType()->isReferenceType()) return 0;
2106
2107 // __block variables can't be allocated in a way that permits NRVO.
2108 if (VD->hasAttr<BlocksAttr>()) return 0;
2109
2110 // Variables with higher required alignment than their type's ABI
2111 // alignment cannot use NRVO.
2112 if (VD->hasAttr<AlignedAttr>() &&
2113 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2114 return 0;
2115
2116 return VD;
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002117}
2118
Douglas Gregor07f402c2011-01-21 21:08:57 +00002119/// \brief Perform the initialization of a potentially-movable value, which
2120/// is the result of return value.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002121///
2122/// This routine implements C++0x [class.copy]p33, which attempts to treat
2123/// returned lvalues as rvalues in certain cases (to prefer move construction),
2124/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125ExprResult
Douglas Gregor07f402c2011-01-21 21:08:57 +00002126Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2127 const VarDecl *NRVOCandidate,
2128 QualType ResultType,
Douglas Gregorbca01b42011-07-06 22:04:06 +00002129 Expr *Value,
2130 bool AllowNRVO) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002131 // C++0x [class.copy]p33:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002132 // When the criteria for elision of a copy operation are met or would
2133 // be met save for the fact that the source object is a function
2134 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorcc15f012011-01-21 19:38:21 +00002135 // overload resolution to select the constructor for the copy is first
2136 // performed as if the object were designated by an rvalue.
Douglas Gregorcc15f012011-01-21 19:38:21 +00002137 ExprResult Res = ExprError();
Douglas Gregorbca01b42011-07-06 22:04:06 +00002138 if (AllowNRVO &&
2139 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smithdbbeccc2012-05-15 05:04:02 +00002141 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002142
Douglas Gregorcc15f012011-01-21 19:38:21 +00002143 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002144 InitializationKind Kind
Douglas Gregor07f402c2011-01-21 21:08:57 +00002145 = InitializationKind::CreateCopy(Value->getLocStart(),
2146 Value->getLocStart());
2147 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148
2149 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorcc15f012011-01-21 19:38:21 +00002150 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002151 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorcc15f012011-01-21 19:38:21 +00002152 // is performed again, considering the object as an lvalue.
Sebastian Redl383616c2011-06-05 12:23:28 +00002153 if (Seq) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00002154 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2155 StepEnd = Seq.step_end();
2156 Step != StepEnd; ++Step) {
Sebastian Redl383616c2011-06-05 12:23:28 +00002157 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorcc15f012011-01-21 19:38:21 +00002158 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159
2160 CXXConstructorDecl *Constructor
Douglas Gregorcc15f012011-01-21 19:38:21 +00002161 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002162
Douglas Gregorcc15f012011-01-21 19:38:21 +00002163 const RValueReferenceType *RRefType
Douglas Gregor07f402c2011-01-21 21:08:57 +00002164 = Constructor->getParamDecl(0)->getType()
2165 ->getAs<RValueReferenceType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002166
Douglas Gregorcc15f012011-01-21 19:38:21 +00002167 // If we don't meet the criteria, break out now.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168 if (!RRefType ||
Douglas Gregor07f402c2011-01-21 21:08:57 +00002169 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2170 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorcc15f012011-01-21 19:38:21 +00002171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002172
Douglas Gregorcc15f012011-01-21 19:38:21 +00002173 // Promote "AsRvalue" to the heap, since we now need this
2174 // expression node to persist.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002175 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smithdbbeccc2012-05-15 05:04:02 +00002176 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002177
Douglas Gregorcc15f012011-01-21 19:38:21 +00002178 // Complete type-checking the initialization of the return type
2179 // using the constructor we found.
Douglas Gregor07f402c2011-01-21 21:08:57 +00002180 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorcc15f012011-01-21 19:38:21 +00002181 }
2182 }
2183 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002184
Douglas Gregorcc15f012011-01-21 19:38:21 +00002185 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002186 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorcc15f012011-01-21 19:38:21 +00002187 // (again) now with the return value expression as written.
2188 if (Res.isInvalid())
Douglas Gregor07f402c2011-01-21 21:08:57 +00002189 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002190
Douglas Gregorcc15f012011-01-21 19:38:21 +00002191 return Res;
2192}
2193
Eli Friedman84b007f2012-01-26 03:00:14 +00002194/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2195/// for capturing scopes.
Steve Naroff4eb206b2008-09-03 18:15:37 +00002196///
John McCall60d7b3a2010-08-24 06:29:42 +00002197StmtResult
Eli Friedman84b007f2012-01-26 03:00:14 +00002198Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2199 // If this is the first return we've seen, infer the return type.
2200 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2201 // rules which allows multiple return statements.
2202 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rose7dd900e2012-07-02 21:19:23 +00002203 QualType FnRetType = CurCap->ReturnType;
2204
2205 // For blocks/lambdas with implicit return types, we check each return
2206 // statement individually, and deduce the common return type when the block
2207 // or lambda is completed.
Eli Friedman84b007f2012-01-26 03:00:14 +00002208 if (CurCap->HasImplicitReturnType) {
Douglas Gregora0c2b212012-02-09 18:40:39 +00002209 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley429bb272011-04-08 18:41:53 +00002210 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2211 if (Result.isInvalid())
2212 return StmtError();
2213 RetValExp = Result.take();
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002214
Jordan Rose7dd900e2012-07-02 21:19:23 +00002215 if (!RetValExp->isTypeDependent())
2216 FnRetType = RetValExp->getType();
2217 else
2218 FnRetType = CurCap->ReturnType = Context.DependentTy;
Douglas Gregora0c2b212012-02-09 18:40:39 +00002219 } else {
2220 if (RetValExp) {
2221 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2222 // initializer list, because it is not an expression (even
2223 // though we represent it as one). We still deduce 'void'.
2224 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2225 << RetValExp->getSourceRange();
2226 }
2227
Jordan Rose7dd900e2012-07-02 21:19:23 +00002228 FnRetType = Context.VoidTy;
Fariborz Jahanian649657e2011-12-03 23:53:56 +00002229 }
Jordan Rose7dd900e2012-07-02 21:19:23 +00002230
2231 // Although we'll properly infer the type of the block once it's completed,
2232 // make sure we provide a return type now for better error recovery.
2233 if (CurCap->ReturnType.isNull())
2234 CurCap->ReturnType = FnRetType;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002235 }
Eli Friedman84b007f2012-01-26 03:00:14 +00002236 assert(!FnRetType.isNull());
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002237
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002238 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman84b007f2012-01-26 03:00:14 +00002239 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2240 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2241 return StmtError();
2242 }
Douglas Gregor793cd1c2012-02-15 16:20:15 +00002243 } else {
2244 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2245 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2246 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2247 return StmtError();
2248 }
2249 }
Mike Stump6c92fa72009-04-29 21:40:37 +00002250
Steve Naroff4eb206b2008-09-03 18:15:37 +00002251 // Otherwise, verify that this result type matches the previous one. We are
2252 // pickier with blocks than for normal functions because we don't have GCC
2253 // compatibility to worry about here.
John McCalld963c372011-08-17 21:34:14 +00002254 const VarDecl *NRVOCandidate = 0;
John McCall0a7efe12011-08-17 22:09:46 +00002255 if (FnRetType->isDependentType()) {
2256 // Delay processing for now. TODO: there are lots of dependent
2257 // types we can conclusively prove aren't void.
2258 } else if (FnRetType->isVoidType()) {
Sebastian Redl5b38a0f2012-02-22 17:38:04 +00002259 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002260 !(getLangOpts().CPlusPlus &&
John McCall0a7efe12011-08-17 22:09:46 +00002261 (RetValExp->isTypeDependent() ||
2262 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002263 if (!getLangOpts().CPlusPlus &&
2264 RetValExp->getType()->isVoidType())
Fariborz Jahanian9354f6a2012-03-21 20:28:39 +00002265 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian4e648e42012-03-21 16:45:13 +00002266 else {
2267 Diag(ReturnLoc, diag::err_return_block_has_expr);
2268 RetValExp = 0;
2269 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00002270 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002271 } else if (!RetValExp) {
John McCall0a7efe12011-08-17 22:09:46 +00002272 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2273 } else if (!RetValExp->isTypeDependent()) {
2274 // we have a non-void block with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002275
John McCall0a7efe12011-08-17 22:09:46 +00002276 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2277 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2278 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002279
John McCall0a7efe12011-08-17 22:09:46 +00002280 // In C++ the return statement is handled via a copy initialization.
2281 // the C version of which boils down to CheckSingleAssignmentConstraints.
2282 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2283 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2284 FnRetType,
Fariborz Jahanian05865202011-12-03 17:47:53 +00002285 NRVOCandidate != 0);
John McCall0a7efe12011-08-17 22:09:46 +00002286 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2287 FnRetType, RetValExp);
2288 if (Res.isInvalid()) {
2289 // FIXME: Cleanup temporaries here, anyway?
2290 return StmtError();
Anders Carlssonc6acbc52010-01-29 18:30:20 +00002291 }
John McCall0a7efe12011-08-17 22:09:46 +00002292 RetValExp = Res.take();
2293 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002294 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002295
John McCalld963c372011-08-17 21:34:14 +00002296 if (RetValExp) {
2297 CheckImplicitConversions(RetValExp, ReturnLoc);
2298 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2299 }
John McCall0a7efe12011-08-17 22:09:46 +00002300 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2301 NRVOCandidate);
John McCalld963c372011-08-17 21:34:14 +00002302
Jordan Rose7dd900e2012-07-02 21:19:23 +00002303 // If we need to check for the named return value optimization,
2304 // or if we need to infer the return type,
2305 // save the return statement in our scope for later processing.
2306 if (CurCap->HasImplicitReturnType ||
2307 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2308 !CurContext->isDependentContext()))
Douglas Gregor5077c382010-05-15 06:01:05 +00002309 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002310
Douglas Gregor5077c382010-05-15 06:01:05 +00002311 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002312}
Reid Spencer5f016e22007-07-11 17:01:13 +00002313
John McCall60d7b3a2010-08-24 06:29:42 +00002314StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002315Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregorfc921372011-05-20 15:32:55 +00002316 // Check for unexpanded parameter packs.
2317 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2318 return StmtError();
2319
Eli Friedman84b007f2012-01-26 03:00:14 +00002320 if (isa<CapturingScopeInfo>(getCurFunction()))
2321 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002322
Chris Lattner371f2582008-12-04 23:50:19 +00002323 QualType FnRetType;
Eli Friedman38ac2432012-03-30 01:13:43 +00002324 QualType RelatedRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +00002325 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +00002326 FnRetType = FD->getResultType();
John McCall04a67a62010-02-05 21:31:56 +00002327 if (FD->hasAttr<NoReturnAttr>() ||
2328 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner86625872009-05-31 19:32:13 +00002329 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedman79430e92012-01-05 00:49:17 +00002330 << FD->getDeclName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002331 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman38ac2432012-03-30 01:13:43 +00002332 FnRetType = MD->getResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00002333 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2334 // In the implementation of a method with a related return type, the
2335 // type used to type-check the validity of return statements within the
2336 // method body is a pointer to the type of the class being implemented.
Eli Friedman38ac2432012-03-30 01:13:43 +00002337 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2338 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor926df6c2011-06-11 01:09:30 +00002339 }
2340 } else // If we don't have a function/method context, bail.
Steve Naroffc97fb9a2009-03-03 00:45:38 +00002341 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Douglas Gregor5077c382010-05-15 06:01:05 +00002343 ReturnStmt *Result = 0;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002344 if (FnRetType->isVoidType()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002345 if (RetValExp) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002346 if (isa<InitListExpr>(RetValExp)) {
2347 // We simply never allow init lists as the return value of void
2348 // functions. This is compatible because this was never allowed before,
2349 // so there's no legacy code to deal with.
2350 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2351 int FunctionKind = 0;
2352 if (isa<ObjCMethodDecl>(CurDecl))
2353 FunctionKind = 1;
2354 else if (isa<CXXConstructorDecl>(CurDecl))
2355 FunctionKind = 2;
2356 else if (isa<CXXDestructorDecl>(CurDecl))
2357 FunctionKind = 3;
2358
2359 Diag(ReturnLoc, diag::err_return_init_list)
2360 << CurDecl->getDeclName() << FunctionKind
2361 << RetValExp->getSourceRange();
2362
2363 // Drop the expression.
2364 RetValExp = 0;
2365 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002366 // C99 6.8.6.4p1 (ext_ since GCC warns)
2367 unsigned D = diag::ext_return_has_expr;
2368 if (RetValExp->getType()->isVoidType())
2369 D = diag::ext_return_has_void_expr;
2370 else {
2371 ExprResult Result = Owned(RetValExp);
2372 Result = IgnoredValueConversions(Result.take());
2373 if (Result.isInvalid())
2374 return StmtError();
2375 RetValExp = Result.take();
2376 RetValExp = ImpCastExprToType(RetValExp,
2377 Context.VoidTy, CK_ToVoid).take();
2378 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002379
Nick Lewycky8d794612011-06-01 07:44:31 +00002380 // return (some void expression); is legal in C++.
2381 if (D != diag::ext_return_has_void_expr ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002382 !getLangOpts().CPlusPlus) {
Nick Lewycky8d794612011-06-01 07:44:31 +00002383 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002384
2385 int FunctionKind = 0;
2386 if (isa<ObjCMethodDecl>(CurDecl))
2387 FunctionKind = 1;
2388 else if (isa<CXXConstructorDecl>(CurDecl))
2389 FunctionKind = 2;
2390 else if (isa<CXXDestructorDecl>(CurDecl))
2391 FunctionKind = 3;
2392
Nick Lewycky8d794612011-06-01 07:44:31 +00002393 Diag(ReturnLoc, D)
Chandler Carruthca0d0d42011-06-30 08:56:22 +00002394 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky8d794612011-06-01 07:44:31 +00002395 << RetValExp->getSourceRange();
2396 }
Chris Lattnere878eb02008-12-18 02:03:48 +00002397 }
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Sebastian Redl33deb352012-02-22 10:50:08 +00002399 if (RetValExp) {
2400 CheckImplicitConversions(RetValExp, ReturnLoc);
2401 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2402 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002404
Douglas Gregor5077c382010-05-15 06:01:05 +00002405 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2406 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002407 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2408 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikie4e4d0842012-03-11 07:00:24 +00002409 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner3c73c412008-11-19 08:23:25 +00002410
2411 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +00002412 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +00002413 else
Chris Lattner08631c52008-11-23 21:45:46 +00002414 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor5077c382010-05-15 06:01:05 +00002415 Result = new (Context) ReturnStmt(ReturnLoc);
2416 } else {
2417 const VarDecl *NRVOCandidate = 0;
2418 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2419 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002420
Eli Friedman38ac2432012-03-30 01:13:43 +00002421 if (!RelatedRetType.isNull()) {
2422 // If we have a related result type, perform an extra conversion here.
2423 // FIXME: The diagnostics here don't really describe what is happening.
2424 InitializedEntity Entity =
2425 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002426
Eli Friedman38ac2432012-03-30 01:13:43 +00002427 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2428 RetValExp);
2429 if (Res.isInvalid()) {
2430 // FIXME: Cleanup temporaries here, anyway?
2431 return StmtError();
2432 }
2433 RetValExp = Res.takeAs<Expr>();
2434 }
2435
Douglas Gregor5077c382010-05-15 06:01:05 +00002436 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2437 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2438 // function return.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002439
John McCall856d3792011-06-16 23:24:51 +00002440 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor5077c382010-05-15 06:01:05 +00002441 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregorf5d8f462011-01-21 18:05:27 +00002442 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002443 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002444 FnRetType,
Francois Pichet58f14c02011-06-02 00:47:27 +00002445 NRVOCandidate != 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002446 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor07f402c2011-01-21 21:08:57 +00002447 FnRetType, RetValExp);
Douglas Gregor5077c382010-05-15 06:01:05 +00002448 if (Res.isInvalid()) {
2449 // FIXME: Cleanup temporaries here, anyway?
2450 return StmtError();
2451 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +00002452
Douglas Gregor5077c382010-05-15 06:01:05 +00002453 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002454 if (RetValExp)
Douglas Gregor5077c382010-05-15 06:01:05 +00002455 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002456 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457
John McCallb4eb64d2010-10-08 02:01:28 +00002458 if (RetValExp) {
2459 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall4765fa02010-12-06 08:20:24 +00002460 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallb4eb64d2010-10-08 02:01:28 +00002461 }
Douglas Gregor5077c382010-05-15 06:01:05 +00002462 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor898574e2008-12-05 23:32:09 +00002463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002464
2465 // If we need to check for the named return value optimization, save the
Douglas Gregor5077c382010-05-15 06:01:05 +00002466 // return statement in our scope for later processing.
David Blaikie4e4d0842012-03-11 07:00:24 +00002467 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor5077c382010-05-15 06:01:05 +00002468 !CurContext->isDependentContext())
2469 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosier8e1e0542012-06-20 18:51:04 +00002470
Douglas Gregor5077c382010-05-15 06:01:05 +00002471 return Owned(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002472}
2473
Chris Lattner810f6d52009-03-13 17:38:01 +00002474/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2475/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2476/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2477/// provide a strong guidance to not use it.
2478///
2479/// This method checks to see if the argument is an acceptable l-value and
2480/// returns false if it is a case we can handle.
2481static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlsson703e3942010-01-24 05:50:09 +00002482 // Type dependent expressions will be checked during instantiation.
2483 if (E->isTypeDependent())
2484 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002485
John McCall7eb0a9e2010-11-24 05:12:34 +00002486 if (E->isLValue())
Chris Lattner810f6d52009-03-13 17:38:01 +00002487 return false; // Cool, this is an lvalue.
2488
2489 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2490 // are supposed to allow.
2491 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall7eb0a9e2010-11-24 05:12:34 +00002492 if (E != E2 && E2->isLValue()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002493 if (!S.getLangOpts().HeinousExtensions)
Chris Lattner810f6d52009-03-13 17:38:01 +00002494 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2495 << E->getSourceRange();
2496 else
2497 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2498 << E->getSourceRange();
2499 // Accept, even if we emitted an error diagnostic.
2500 return false;
2501 }
2502
2503 // None of the above, just randomly invalid non-lvalue.
2504 return true;
2505}
2506
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002507/// isOperandMentioned - Return true if the specified operand # is mentioned
2508/// anywhere in the decomposed asm string.
2509static bool isOperandMentioned(unsigned OpNo,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002510 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002511 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2512 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2513 if (!Piece.isOperand()) continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002514
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002515 // If this is a reference to the input and if the input was the smaller
2516 // one, then we have to reject this asm.
2517 if (Piece.getOperandNo() == OpNo)
2518 return true;
2519 }
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002520 return false;
2521}
Chris Lattner810f6d52009-03-13 17:38:01 +00002522
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002523StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2524 bool IsVolatile, unsigned NumOutputs,
2525 unsigned NumInputs, IdentifierInfo **Names,
2526 MultiExprArg constraints, MultiExprArg exprs,
2527 Expr *asmString, MultiExprArg clobbers,
2528 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002529 unsigned NumClobbers = clobbers.size();
2530 StringLiteral **Constraints =
2531 reinterpret_cast<StringLiteral**>(constraints.get());
John McCall9ae2f072010-08-23 23:25:46 +00002532 Expr **Exprs = exprs.get();
2533 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl3037ed02009-01-18 16:53:17 +00002534 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2535
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Chris Lattner1708b962008-08-18 19:55:17 +00002538 // The parser verifies that there is a string literal here.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002539 if (!AsmString->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002540 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2541 << AsmString->getSourceRange());
2542
Chris Lattner1708b962008-08-18 19:55:17 +00002543 for (unsigned i = 0; i != NumOutputs; i++) {
2544 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002545 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002546 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2547 << Literal->getSourceRange());
2548
Chris Lattner5f9e2722011-07-23 10:55:15 +00002549 StringRef OutputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002550 if (Names[i])
2551 OutputName = Names[i]->getName();
2552
2553 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002554 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002555 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002556 diag::err_asm_invalid_output_constraint)
2557 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00002558
Anders Carlssond04c6e22007-11-27 04:11:28 +00002559 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00002560 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00002561 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00002562 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002563 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00002564 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002565 }
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Chris Lattner44def072009-04-26 07:16:29 +00002567 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002568 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002569
Chris Lattner5f9e2722011-07-23 10:55:15 +00002570 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner806503f2009-05-03 05:55:43 +00002571
Anders Carlsson04728b72007-11-23 19:43:50 +00002572 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00002573 StringLiteral *Literal = Constraints[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002574 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002575 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2576 << Literal->getSourceRange());
2577
Chris Lattner5f9e2722011-07-23 10:55:15 +00002578 StringRef InputName;
Anders Carlssonff93dbd2010-01-30 22:25:16 +00002579 if (Names[i])
2580 InputName = Names[i]->getName();
2581
2582 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002583 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00002584 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00002585 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00002586 diag::err_asm_invalid_input_constraint)
2587 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00002588 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002589
Eli Friedman72056a22009-05-03 07:49:42 +00002590 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00002591
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002592 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00002593 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00002594 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00002595 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002596 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00002597 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002598 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00002599 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002600
Chris Lattner44def072009-04-26 07:16:29 +00002601 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002602 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00002603 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002604 diag::err_asm_invalid_type_in_input)
Mike Stump1eb44332009-09-09 15:08:12 +00002605 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00002606 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002607 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00002608 }
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John Wiegley429bb272011-04-08 18:41:53 +00002610 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2611 if (Result.isInvalid())
2612 return StmtError();
Mike Stump1eb44332009-09-09 15:08:12 +00002613
John Wiegley429bb272011-04-08 18:41:53 +00002614 Exprs[i] = Result.take();
Chris Lattner806503f2009-05-03 05:55:43 +00002615 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00002616 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002617
Anders Carlsson6fa90862007-11-25 00:25:21 +00002618 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00002619 for (unsigned i = 0; i != NumClobbers; i++) {
2620 StringLiteral *Literal = Clobbers[i];
Douglas Gregor5cee1192011-07-27 05:40:30 +00002621 if (!Literal->isAscii())
Sebastian Redl3037ed02009-01-18 16:53:17 +00002622 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2623 << Literal->getSourceRange());
2624
Chris Lattner5f9e2722011-07-23 10:55:15 +00002625 StringRef Clobber = Literal->getString();
Sebastian Redl3037ed02009-01-18 16:53:17 +00002626
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002627 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl3037ed02009-01-18 16:53:17 +00002628 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00002629 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00002630 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00002631
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002632 AsmStmt *NS =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002633 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2634 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson966146e2010-01-30 23:19:41 +00002635 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002636 // Validate the asm string, ensuring it makes sense given the operands we
2637 // have.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002638 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002639 unsigned DiagOffs;
2640 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00002641 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2642 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002643 return StmtError();
2644 }
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Chris Lattner806503f2009-05-03 05:55:43 +00002646 // Validate tied input operands for type mismatches.
2647 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2648 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Chris Lattner806503f2009-05-03 05:55:43 +00002650 // If this is a tied constraint, verify that the output and input have
2651 // either exactly the same type, or that they are int/ptr operands with the
2652 // same size (int/long, int*/long, are ok etc).
2653 if (!Info.hasTiedOperand()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Chris Lattner806503f2009-05-03 05:55:43 +00002655 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner935f0f02011-02-21 22:09:29 +00002656 unsigned InputOpNo = i+NumOutputs;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00002657 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner935f0f02011-02-21 22:09:29 +00002658 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedmanf45b3572011-09-14 19:20:00 +00002659
2660 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2661 continue;
2662
Chris Lattner7adaa182009-05-03 05:59:17 +00002663 QualType InTy = InputExpr->getType();
2664 QualType OutTy = OutputExpr->getType();
2665 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00002666 continue; // All types can be tied to themselves.
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Chris Lattneraab64d02010-04-23 17:27:29 +00002668 // Decide if the input and output are in the same domain (integer/ptr or
2669 // floating point.
2670 enum AsmDomain {
2671 AD_Int, AD_FP, AD_Other
2672 } InputDomain, OutputDomain;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002673
Chris Lattneraab64d02010-04-23 17:27:29 +00002674 if (InTy->isIntegerType() || InTy->isPointerType())
2675 InputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002676 else if (InTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002677 InputDomain = AD_FP;
2678 else
2679 InputDomain = AD_Other;
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattneraab64d02010-04-23 17:27:29 +00002681 if (OutTy->isIntegerType() || OutTy->isPointerType())
2682 OutputDomain = AD_Int;
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002683 else if (OutTy->isRealFloatingType())
Chris Lattneraab64d02010-04-23 17:27:29 +00002684 OutputDomain = AD_FP;
2685 else
2686 OutputDomain = AD_Other;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002687
Chris Lattneraab64d02010-04-23 17:27:29 +00002688 // They are ok if they are the same size and in the same domain. This
2689 // allows tying things like:
2690 // void* to int*
2691 // void* to int if they are the same size.
2692 // double to long double if they are the same size.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002693 //
Chris Lattneraab64d02010-04-23 17:27:29 +00002694 uint64_t OutSize = Context.getTypeSize(OutTy);
2695 uint64_t InSize = Context.getTypeSize(InTy);
2696 if (OutSize == InSize && InputDomain == OutputDomain &&
2697 InputDomain != AD_Other)
2698 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699
Chris Lattneraab64d02010-04-23 17:27:29 +00002700 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002701 // then we can promote the smaller one to a larger input and the asm string
2702 // won't notice.
Chris Lattneraab64d02010-04-23 17:27:29 +00002703 bool SmallerValueMentioned = false;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002704
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002705 // If this is a reference to the input and if the input was the smaller
2706 // one, then we have to reject this asm.
Chris Lattner935f0f02011-02-21 22:09:29 +00002707 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002708 // This is a use in the asm string of the smaller operand. Since we
2709 // codegen this by promoting to a wider value, the asm will get printed
2710 // "wrong".
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002711 SmallerValueMentioned |= InSize < OutSize;
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002712 }
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002713 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattnerca57b4b2011-02-21 21:40:33 +00002714 // If this is a reference to the output, and if the output is the larger
2715 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnerf0c4d282011-02-21 21:50:25 +00002716 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner806503f2009-05-03 05:55:43 +00002717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Chris Lattneraab64d02010-04-23 17:27:29 +00002719 // If the smaller value wasn't mentioned in the asm string, and if the
2720 // output was a register, just extend the shorter one to the size of the
2721 // larger one.
2722 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2723 OutputConstraintInfos[TiedTo].allowsRegister())
2724 continue;
Chad Rosier8e1e0542012-06-20 18:51:04 +00002725
Chris Lattner935f0f02011-02-21 22:09:29 +00002726 // Either both of the operands were mentioned or the smaller one was
2727 // mentioned. One more special case that we'll allow: if the tied input is
2728 // integer, unmentioned, and is a constant, then we'll allow truncating it
2729 // down to the size of the destination.
2730 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2731 !isOperandMentioned(InputOpNo, Pieces) &&
2732 InputExpr->isEvaluatable(Context)) {
John McCall4da89c82011-05-10 23:39:47 +00002733 CastKind castKind =
2734 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2735 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner935f0f02011-02-21 22:09:29 +00002736 Exprs[InputOpNo] = InputExpr;
2737 NS->setInputExpr(i, InputExpr);
2738 continue;
2739 }
Chad Rosier8e1e0542012-06-20 18:51:04 +00002740
Chris Lattnerc1f3b282009-05-03 06:50:40 +00002741 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00002742 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00002743 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00002744 << InputExpr->getSourceRange();
Chris Lattner806503f2009-05-03 05:55:43 +00002745 return StmtError();
2746 }
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Chris Lattnerfb5058e2009-03-10 23:41:04 +00002748 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00002749}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002750
Chad Rosiere696b692012-08-08 18:22:06 +00002751// needSpaceAsmToken - This function handles whitespace around asm punctuation.
2752// Returns true if a space should be emitted.
Chad Rosiere696b692012-08-08 18:22:06 +00002753static inline bool needSpaceAsmToken(Token currTok) {
2754 static Token prevTok;
2755
2756 // No need for space after prevToken.
2757 switch(prevTok.getKind()) {
2758 default:
2759 break;
2760 case tok::l_square:
2761 case tok::r_square:
2762 case tok::l_brace:
2763 case tok::r_brace:
2764 case tok::colon:
2765 prevTok = currTok;
2766 return false;
2767 }
2768
2769 // No need for a space before currToken.
2770 switch(currTok.getKind()) {
2771 default:
2772 break;
2773 case tok::l_square:
2774 case tok::r_square:
2775 case tok::l_brace:
2776 case tok::r_brace:
2777 case tok::comma:
2778 case tok::colon:
2779 prevTok = currTok;
2780 return false;
2781 }
2782 prevTok = currTok;
2783 return true;
2784}
2785
2786static std::string PatchMSAsmString(Sema &SemaRef, bool &IsSimple,
2787 SourceLocation AsmLoc,
2788 ArrayRef<Token> AsmToks,
2789 const TargetInfo &TI) {
Chad Rosier871ee562012-08-08 21:08:20 +00002790 // Assume simple asm stmt until we parse a non-register identifer.
2791 IsSimple = true;
2792
Chad Rosier77c7b0a2012-08-08 21:42:11 +00002793 if (AsmToks.empty())
Chad Rosierb64f3102012-08-08 20:37:31 +00002794 return "";
2795
Chad Rosiere696b692012-08-08 18:22:06 +00002796 std::string Res;
2797 IdentifierInfo *II = AsmToks[0].getIdentifierInfo();
2798 Res = II->getName().str();
2799
Chad Rosiere696b692012-08-08 18:22:06 +00002800 // Check the operands.
2801 for (unsigned i = 1, e = AsmToks.size(); i != e; ++i) {
2802 if (needSpaceAsmToken(AsmToks[i]))
2803 Res += " ";
2804
2805 switch (AsmToks[i].getKind()) {
2806 default:
2807 //llvm_unreachable("Unknown token.");
2808 break;
2809 case tok::comma: Res += ","; break;
2810 case tok::colon: Res += ":"; break;
2811 case tok::l_square: Res += "["; break;
2812 case tok::r_square: Res += "]"; break;
2813 case tok::l_brace: Res += "{"; break;
2814 case tok::r_brace: Res += "}"; break;
2815 case tok::numeric_constant: {
2816 SmallString<32> TokenBuf;
2817 TokenBuf.resize(32);
2818 bool StringInvalid = false;
2819 const char *ThisTokBuf = &TokenBuf[0];
2820 unsigned ThisTokLen =
2821 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2822 SemaRef.getLangOpts(), &StringInvalid);
2823 Res += StringRef(ThisTokBuf, ThisTokLen);
2824 break;
2825 }
2826 case tok::identifier: {
2827 II = AsmToks[i].getIdentifierInfo();
2828 StringRef Name = II->getName();
2829
2830 // Valid registers don't need modification.
2831 if (TI.isValidGCCRegisterName(Name)) {
2832 Res += Name;
2833 break;
2834 }
2835
2836 // TODO: Lookup the identifier.
2837 IsSimple = false;
2838 }
2839 } // AsmToks[i].getKind()
2840 }
2841 return Res;
2842}
2843
Chad Rosier62f22b82012-08-08 19:48:07 +00002844// Build the unmodified MSAsmString.
2845static std::string buildMSAsmString(Sema &SemaRef,
2846 ArrayRef<Token> AsmToks,
2847 ArrayRef<unsigned> LineEnds) {
Chad Rosier77c7b0a2012-08-08 21:42:11 +00002848 if (AsmToks.empty())
Chad Rosierb64f3102012-08-08 20:37:31 +00002849 return "";
2850
Chad Rosier62f22b82012-08-08 19:48:07 +00002851 SmallString<512> Asm;
2852 SmallString<512> TokenBuf;
2853 TokenBuf.resize(512);
2854 unsigned AsmLineNum = 0;
2855 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2856 const char *ThisTokBuf = &TokenBuf[0];
2857 bool StringInvalid = false;
2858 unsigned ThisTokLen =
2859 Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2860 SemaRef.getLangOpts(), &StringInvalid);
2861 if (i && (!AsmLineNum || i != LineEnds[AsmLineNum-1]) &&
2862 needSpaceAsmToken(AsmToks[i]))
2863 Asm += ' ';
2864 Asm += StringRef(ThisTokBuf, ThisTokLen);
2865 if (i + 1 == LineEnds[AsmLineNum] && i + 1 != AsmToks.size()) {
2866 Asm += '\n';
2867 ++AsmLineNum;
2868 }
2869 }
2870 return Asm.c_str();
2871}
2872
Chad Rosier8cd64b42012-06-11 20:47:18 +00002873StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
Chad Rosier79efe242012-08-07 00:29:06 +00002874 ArrayRef<Token> AsmToks,
Chad Rosier62f22b82012-08-08 19:48:07 +00002875 ArrayRef<unsigned> LineEnds,
Chad Rosier8cd64b42012-06-11 20:47:18 +00002876 SourceLocation EndLoc) {
Chad Rosier52e4ed92012-06-20 18:28:37 +00002877 // MS-style inline assembly is not fully supported, so emit a warning.
2878 Diag(AsmLoc, diag::warn_unsupported_msasm);
2879
Chad Rosier62f22b82012-08-08 19:48:07 +00002880 std::string AsmString = buildMSAsmString(*this, AsmToks, LineEnds);
2881
Chad Rosiere696b692012-08-08 18:22:06 +00002882 bool IsSimple;
2883 // Rewrite operands to appease the AsmParser.
2884 std::string PatchedAsmString =
2885 PatchMSAsmString(*this, IsSimple, AsmLoc, AsmToks, Context.getTargetInfo());
2886
2887 // Silence compiler warnings. Eventually, the PatchedAsmString will be
2888 // passed to the AsmParser.
2889 (void)PatchedAsmString;
2890
Chad Rosierbe3d0db2012-08-09 17:33:11 +00002891 // Initialize targets and assembly printers/parsers.
2892 llvm::InitializeAllTargetInfos();
2893 llvm::InitializeAllTargetMCs();
2894 llvm::InitializeAllAsmParsers();
2895
Chad Rosier8cd64b42012-06-11 20:47:18 +00002896 MSAsmStmt *NS =
Chad Rosiere696b692012-08-08 18:22:06 +00002897 new (Context) MSAsmStmt(Context, AsmLoc, IsSimple, /* IsVolatile */ true,
Chad Rosier62f22b82012-08-08 19:48:07 +00002898 AsmToks, LineEnds, AsmString, EndLoc);
Chad Rosier8cd64b42012-06-11 20:47:18 +00002899
2900 return Owned(NS);
2901}
2902
John McCall60d7b3a2010-08-24 06:29:42 +00002903StmtResult
Sebastian Redl431e90e2009-01-18 17:43:11 +00002904Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCalld226f652010-08-21 09:40:31 +00002905 SourceLocation RParen, Decl *Parm,
John McCall9ae2f072010-08-23 23:25:46 +00002906 Stmt *Body) {
John McCalld226f652010-08-21 09:40:31 +00002907 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00002908 if (Var && Var->isInvalidDecl())
2909 return StmtError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002910
John McCall9ae2f072010-08-23 23:25:46 +00002911 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00002912}
2913
John McCall60d7b3a2010-08-24 06:29:42 +00002914StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002915Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2916 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00002917}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002918
John McCall60d7b3a2010-08-24 06:29:42 +00002919StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002920Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCall9ae2f072010-08-23 23:25:46 +00002921 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002922 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002923 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2924
John McCall781472f2010-08-25 08:40:02 +00002925 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002926 unsigned NumCatchStmts = CatchStmts.size();
John McCall9ae2f072010-08-23 23:25:46 +00002927 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2928 CatchStmts.release(),
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002929 NumCatchStmts,
John McCall9ae2f072010-08-23 23:25:46 +00002930 Finally));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002931}
2932
John McCalld1376ee2012-05-08 21:41:25 +00002933StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregord1377b22010-04-22 21:44:01 +00002934 if (Throw) {
John Wiegley429bb272011-04-08 18:41:53 +00002935 ExprResult Result = DefaultLvalueConversion(Throw);
2936 if (Result.isInvalid())
2937 return StmtError();
John McCall5e3c67b2010-12-15 04:42:30 +00002938
John McCalld1376ee2012-05-08 21:41:25 +00002939 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregord1377b22010-04-22 21:44:01 +00002940 QualType ThrowType = Throw->getType();
2941 // Make sure the expression type is an ObjC pointer or "void *".
2942 if (!ThrowType->isDependentType() &&
2943 !ThrowType->isObjCObjectPointerType()) {
2944 const PointerType *PT = ThrowType->getAs<PointerType>();
2945 if (!PT || !PT->getPointeeType()->isVoidType())
2946 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2947 << Throw->getType() << Throw->getSourceRange());
2948 }
2949 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002950
John McCall9ae2f072010-08-23 23:25:46 +00002951 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregord1377b22010-04-22 21:44:01 +00002952}
2953
John McCall60d7b3a2010-08-24 06:29:42 +00002954StmtResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregord1377b22010-04-22 21:44:01 +00002956 Scope *CurScope) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002957 if (!getLangOpts().ObjCExceptions)
Anders Carlssonda4b7cf2011-02-19 23:53:54 +00002958 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2959
John McCall9ae2f072010-08-23 23:25:46 +00002960 if (!Throw) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00002961 // @throw without an expression designates a rethrow (which much occur
2962 // in the context of an @catch clause).
2963 Scope *AtCatchParent = CurScope;
2964 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2965 AtCatchParent = AtCatchParent->getParent();
2966 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00002967 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968 }
John McCall9ae2f072010-08-23 23:25:46 +00002969 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00002970}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00002971
John McCall07524032011-07-27 21:50:02 +00002972ExprResult
2973Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2974 ExprResult result = DefaultLvalueConversion(operand);
2975 if (result.isInvalid())
2976 return ExprError();
2977 operand = result.take();
2978
2979 // Make sure the expression type is an ObjC pointer or "void *".
2980 QualType type = operand->getType();
2981 if (!type->isDependentType() &&
2982 !type->isObjCObjectPointerType()) {
2983 const PointerType *pointerType = type->getAs<PointerType>();
2984 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2985 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2986 << type << operand->getSourceRange();
2987 }
2988
2989 // The operand to @synchronized is a full-expression.
2990 return MaybeCreateExprWithCleanups(operand);
2991}
2992
John McCall60d7b3a2010-08-24 06:29:42 +00002993StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00002994Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2995 Stmt *SyncBody) {
John McCall07524032011-07-27 21:50:02 +00002996 // We can't jump into or indirect-jump out of a @synchronized block.
John McCall781472f2010-08-25 08:40:02 +00002997 getCurFunction()->setHasBranchProtectedScope();
John McCall9ae2f072010-08-23 23:25:46 +00002998 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00002999}
Sebastian Redl4b07b292008-12-22 19:15:10 +00003000
3001/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3002/// and creates a proper catch handler from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003003StmtResult
John McCalld226f652010-08-21 09:40:31 +00003004Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCall9ae2f072010-08-23 23:25:46 +00003005 Stmt *HandlerBlock) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003006 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003007 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCalld226f652010-08-21 09:40:31 +00003008 cast_or_null<VarDecl>(ExDecl),
John McCall9ae2f072010-08-23 23:25:46 +00003009 HandlerBlock));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003010}
Sebastian Redl8351da02008-12-22 21:35:02 +00003011
John McCallf85e1932011-06-15 23:02:42 +00003012StmtResult
3013Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3014 getCurFunction()->setHasBranchProtectedScope();
3015 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3016}
3017
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003018namespace {
3019
Sebastian Redlc447aba2009-07-29 17:15:45 +00003020class TypeWithHandler {
3021 QualType t;
3022 CXXCatchStmt *stmt;
3023public:
3024 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3025 : t(type), stmt(statement) {}
3026
John McCall0953e762009-09-24 19:53:00 +00003027 // An arbitrary order is fine as long as it places identical
3028 // types next to each other.
Sebastian Redlc447aba2009-07-29 17:15:45 +00003029 bool operator<(const TypeWithHandler &y) const {
John McCall0953e762009-09-24 19:53:00 +00003030 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003031 return true;
John McCall0953e762009-09-24 19:53:00 +00003032 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redlc447aba2009-07-29 17:15:45 +00003033 return false;
3034 else
3035 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3036 }
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Sebastian Redlc447aba2009-07-29 17:15:45 +00003038 bool operator==(const TypeWithHandler& other) const {
John McCall0953e762009-09-24 19:53:00 +00003039 return t == other.t;
Sebastian Redlc447aba2009-07-29 17:15:45 +00003040 }
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Sebastian Redlc447aba2009-07-29 17:15:45 +00003042 CXXCatchStmt *getCatchStmt() const { return stmt; }
3043 SourceLocation getTypeSpecStartLoc() const {
3044 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3045 }
3046};
3047
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003048}
3049
Sebastian Redl8351da02008-12-22 21:35:02 +00003050/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3051/// handlers and creates a try statement from them.
John McCall60d7b3a2010-08-24 06:29:42 +00003052StmtResult
John McCall9ae2f072010-08-23 23:25:46 +00003053Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl8351da02008-12-22 21:35:02 +00003054 MultiStmtArg RawHandlers) {
Anders Carlsson729b8532011-02-23 03:46:46 +00003055 // Don't report an error if 'try' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003056 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +00003057 !getSourceManager().isInSystemHeader(TryLoc))
3058 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson7f11d9c2011-02-19 19:26:44 +00003059
Sebastian Redl8351da02008-12-22 21:35:02 +00003060 unsigned NumHandlers = RawHandlers.size();
3061 assert(NumHandlers > 0 &&
3062 "The parser shouldn't call this if there are no handlers.");
John McCall9ae2f072010-08-23 23:25:46 +00003063 Stmt **Handlers = RawHandlers.get();
Sebastian Redl8351da02008-12-22 21:35:02 +00003064
Chris Lattner5f9e2722011-07-23 10:55:15 +00003065 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump1eb44332009-09-09 15:08:12 +00003066
3067 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003068 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00003069 if (!Handler->getExceptionDecl()) {
3070 if (i < NumHandlers - 1)
3071 return StmtError(Diag(Handler->getLocStart(),
3072 diag::err_early_catch_all));
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Sebastian Redlc447aba2009-07-29 17:15:45 +00003074 continue;
3075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Sebastian Redlc447aba2009-07-29 17:15:45 +00003077 const QualType CaughtType = Handler->getCaughtType();
3078 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3079 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00003080 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00003081
3082 // Detect handlers for the same type as an earlier one.
3083 if (NumHandlers > 1) {
3084 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Sebastian Redlc447aba2009-07-29 17:15:45 +00003086 TypeWithHandler prev = TypesWithHandlers[0];
3087 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3088 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Sebastian Redlc447aba2009-07-29 17:15:45 +00003090 if (curr == prev) {
3091 Diag(curr.getTypeSpecStartLoc(),
3092 diag::warn_exception_caught_by_earlier_handler)
3093 << curr.getCatchStmt()->getCaughtType().getAsString();
3094 Diag(prev.getTypeSpecStartLoc(),
3095 diag::note_previous_exception_handler)
3096 << prev.getCatchStmt()->getCaughtType().getAsString();
3097 }
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Sebastian Redlc447aba2009-07-29 17:15:45 +00003099 prev = curr;
3100 }
3101 }
Mike Stump1eb44332009-09-09 15:08:12 +00003102
John McCall781472f2010-08-25 08:40:02 +00003103 getCurFunction()->setHasBranchProtectedScope();
John McCallb60a77e2010-08-01 00:26:45 +00003104
Sebastian Redl8351da02008-12-22 21:35:02 +00003105 // FIXME: We should detect handlers that cannot catch anything because an
3106 // earlier handler catches a superclass. Need to find a method that is not
3107 // quadratic for this.
3108 // Neither of these are explicitly forbidden, but every compiler detects them
3109 // and warns.
3110
John McCall9ae2f072010-08-23 23:25:46 +00003111 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga1a396d2010-02-03 03:56:39 +00003112 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00003113}
John Wiegley28bbe4b2011-04-28 01:08:34 +00003114
3115StmtResult
3116Sema::ActOnSEHTryBlock(bool IsCXXTry,
3117 SourceLocation TryLoc,
3118 Stmt *TryBlock,
3119 Stmt *Handler) {
3120 assert(TryBlock && Handler);
3121
3122 getCurFunction()->setHasBranchProtectedScope();
3123
3124 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3125}
3126
3127StmtResult
3128Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3129 Expr *FilterExpr,
3130 Stmt *Block) {
3131 assert(FilterExpr && Block);
3132
3133 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichet58f14c02011-06-02 00:47:27 +00003134 return StmtError(Diag(FilterExpr->getExprLoc(),
3135 diag::err_filter_expression_integral)
3136 << FilterExpr->getType());
John Wiegley28bbe4b2011-04-28 01:08:34 +00003137 }
3138
3139 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3140}
3141
3142StmtResult
3143Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3144 Stmt *Block) {
3145 assert(Block);
3146 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3147}
Douglas Gregorba0513d2011-10-25 01:33:02 +00003148
3149StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3150 bool IsIfExists,
3151 NestedNameSpecifierLoc QualifierLoc,
3152 DeclarationNameInfo NameInfo,
3153 Stmt *Nested)
3154{
3155 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3156 QualifierLoc, NameInfo,
3157 cast<CompoundStmt>(Nested));
3158}
3159
3160
3161StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3162 bool IsIfExists,
3163 CXXScopeSpec &SS,
3164 UnqualifiedId &Name,
3165 Stmt *Nested) {
3166 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3167 SS.getWithLocInContext(Context),
3168 GetNameFromUnqualifiedId(Name),
3169 Nested);
3170}