blob: 19a802e452dbc02e220bbf213f3fd7e2abb06b3e [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
14#include "Sema.h"
Anders Carlsson51fe9962008-11-22 21:04:56 +000015#include "clang/AST/APValue.h"
Chris Lattnerf4021e72007-08-23 05:46:52 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner419cfb32009-08-16 16:57:27 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000019#include "clang/AST/StmtObjC.h"
20#include "clang/AST/StmtCXX.h"
Anders Carlsson6fa90862007-11-25 00:25:21 +000021#include "clang/Basic/TargetInfo.h"
Sebastian Redlc447aba2009-07-29 17:15:45 +000022#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallVector.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Anders Carlsson6b1d2832009-05-17 21:11:30 +000026Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
27 Expr *E = expr->takeAs<Expr>();
Steve Naroff1b273c42007-09-16 14:56:35 +000028 assert(E && "ActOnExprStmt(): missing expression");
Sebastian Redla60528c2008-12-21 12:04:03 +000029
Chris Lattner834a72a2008-07-25 23:18:17 +000030 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
31 // void expression for its side effects. Conversion to void allows any
32 // operand, even incomplete types.
Sebastian Redla60528c2008-12-21 12:04:03 +000033
Chris Lattner834a72a2008-07-25 23:18:17 +000034 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redla60528c2008-12-21 12:04:03 +000035 return Owned(static_cast<Stmt*>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
38
Sebastian Redla60528c2008-12-21 12:04:03 +000039Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
Ted Kremenek8189cde2009-02-07 01:47:29 +000040 return Owned(new (Context) NullStmt(SemiLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattner682bf922009-03-29 16:50:03 +000043Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
Sebastian Redla60528c2008-12-21 12:04:03 +000044 SourceLocation StartLoc,
45 SourceLocation EndLoc) {
Chris Lattner682bf922009-03-29 16:50:03 +000046 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Chris Lattner20401692009-04-12 20:13:14 +000047
48 // If we have an invalid decl, just return an error.
49 if (DG.isNull()) return StmtError();
50
Chris Lattner24e1e702009-03-04 04:23:07 +000051 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +000052}
53
Anders Carlsson636463e2009-07-30 22:17:18 +000054void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Anders Carlsson75443112009-07-30 22:39:03 +000055 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson636463e2009-07-30 22:17:18 +000056 if (!E)
57 return;
58
59 // Ignore expressions that have void type.
60 if (E->getType()->isVoidType())
61 return;
62
63 SourceLocation Loc;
64 SourceRange R1, R2;
65 if (!E->isUnusedResultAWarning(Loc, R1, R2))
66 return;
67
Chris Lattner419cfb32009-08-16 16:57:27 +000068 // Okay, we have an unused result. Depending on what the base expression is,
69 // we might want to make a more specific diagnostic. Check for one of these
70 // cases now.
71 unsigned DiagID = diag::warn_unused_expr;
72 E = E->IgnoreParens();
Fariborz Jahanian154440e2009-08-18 20:50:23 +000073 if (isa<ObjCImplctSetterGetterRefExpr>(E))
Chris Lattner419cfb32009-08-16 16:57:27 +000074 DiagID = diag::warn_unused_property_expr;
75
76 Diag(Loc, DiagID) << R1 << R2;
Anders Carlsson636463e2009-07-30 22:17:18 +000077}
78
Sebastian Redla60528c2008-12-21 12:04:03 +000079Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redla60528c2008-12-21 12:04:03 +000081 MultiStmtArg elts, bool isStmtExpr) {
82 unsigned NumElts = elts.size();
83 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerc30ebfb2007-08-27 04:29:41 +000084 // If we're in C89 mode, check that we don't have any decls after stmts. If
85 // so, emit an extension diagnostic.
86 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
87 // Note that __extension__ can be around a decl.
88 unsigned i = 0;
89 // Skip over all declarations.
90 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
91 /*empty*/;
92
93 // We found the end of the list or a statement. Scan for another declstmt.
94 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
95 /*empty*/;
96
97 if (i != NumElts) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +000098 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerc30ebfb2007-08-27 04:29:41 +000099 Diag(D->getLocation(), diag::ext_mixed_decls_code);
100 }
101 }
Chris Lattner98414c12007-08-31 21:49:55 +0000102 // Warn about unused expressions in statements.
103 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson636463e2009-07-30 22:17:18 +0000104 // Ignore statements that are last in a statement expression.
105 if (isStmtExpr && i == NumElts - 1)
Chris Lattner98414c12007-08-31 21:49:55 +0000106 continue;
107
Anders Carlsson636463e2009-07-30 22:17:18 +0000108 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattner98414c12007-08-31 21:49:55 +0000109 }
Sebastian Redla60528c2008-12-21 12:04:03 +0000110
Ted Kremenek8189cde2009-02-07 01:47:29 +0000111 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Reid Spencer5f016e22007-07-11 17:01:13 +0000112}
113
Sebastian Redl117054a2008-12-28 16:13:43 +0000114Action::OwningStmtResult
115Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
116 SourceLocation DotDotDotLoc, ExprArg rhsval,
Chris Lattner24e1e702009-03-04 04:23:07 +0000117 SourceLocation ColonLoc) {
Sebastian Redl117054a2008-12-28 16:13:43 +0000118 assert((lhsval.get() != 0) && "missing expression in case statement");
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 // C99 6.8.4.2p3: The expression shall be an integer constant.
Anders Carlsson51fe9962008-11-22 21:04:56 +0000121 // However, GCC allows any evaluatable integer expression.
Sebastian Redl117054a2008-12-28 16:13:43 +0000122 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000123 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
124 VerifyIntegerConstantExpression(LHSVal))
Chris Lattner24e1e702009-03-04 04:23:07 +0000125 return StmtError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000126
Chris Lattner6c36be52007-07-18 02:28:47 +0000127 // GCC extension: The expression shall be an integer constant.
Sebastian Redl117054a2008-12-28 16:13:43 +0000128
129 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
Douglas Gregordbb26db2009-05-15 23:57:33 +0000130 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
131 VerifyIntegerConstantExpression(RHSVal)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000132 RHSVal = 0; // Recover by just forgetting about it.
Sebastian Redl117054a2008-12-28 16:13:43 +0000133 rhsval = 0;
134 }
135
Chris Lattnerbcfce662009-04-18 20:10:59 +0000136 if (getSwitchStack().empty()) {
Chris Lattner8a87e572007-07-23 17:05:23 +0000137 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner24e1e702009-03-04 04:23:07 +0000138 return StmtError();
Chris Lattner8a87e572007-07-23 17:05:23 +0000139 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140
Sebastian Redl117054a2008-12-28 16:13:43 +0000141 // Only now release the smart pointers.
142 lhsval.release();
143 rhsval.release();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000144 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
145 ColonLoc);
Chris Lattnerbcfce662009-04-18 20:10:59 +0000146 getSwitchStack().back()->addSwitchCase(CS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000147 return Owned(CS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000148}
149
Chris Lattner24e1e702009-03-04 04:23:07 +0000150/// ActOnCaseStmtBody - This installs a statement as the body of a case.
151void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
152 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000153 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Chris Lattner24e1e702009-03-04 04:23:07 +0000154 CS->setSubStmt(SubStmt);
155}
156
Sebastian Redl117054a2008-12-28 16:13:43 +0000157Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000158Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
Sebastian Redl117054a2008-12-28 16:13:43 +0000159 StmtArg subStmt, Scope *CurScope) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000160 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Sebastian Redl117054a2008-12-28 16:13:43 +0000161
Chris Lattnerbcfce662009-04-18 20:10:59 +0000162 if (getSwitchStack().empty()) {
Chris Lattner0fa152e2007-07-21 03:00:26 +0000163 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl117054a2008-12-28 16:13:43 +0000164 return Owned(SubStmt);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000165 }
Sebastian Redl117054a2008-12-28 16:13:43 +0000166
Douglas Gregordbb26db2009-05-15 23:57:33 +0000167 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
Chris Lattnerbcfce662009-04-18 20:10:59 +0000168 getSwitchStack().back()->addSwitchCase(DS);
Sebastian Redl117054a2008-12-28 16:13:43 +0000169 return Owned(DS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000170}
171
Sebastian Redlde307472009-01-11 00:38:46 +0000172Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000173Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
Sebastian Redlde307472009-01-11 00:38:46 +0000174 SourceLocation ColonLoc, StmtArg subStmt) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000175 Stmt *SubStmt = subStmt.takeAs<Stmt>();
Steve Narofff3cf8972009-02-28 16:48:43 +0000176 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +0000177 LabelStmt *&LabelDecl = getLabelMap()[II];
Steve Narofff3cf8972009-02-28 16:48:43 +0000178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // If not forward referenced or defined already, just create a new LabelStmt.
Steve Naroffcaaacec2009-03-13 15:38:40 +0000180 if (LabelDecl == 0)
181 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
Sebastian Redlde307472009-01-11 00:38:46 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 assert(LabelDecl->getID() == II && "Label mismatch!");
Sebastian Redlde307472009-01-11 00:38:46 +0000184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // Otherwise, this label was either forward reference or multiply defined. If
186 // multiply defined, reject it now.
187 if (LabelDecl->getSubStmt()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000188 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000189 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
Sebastian Redlde307472009-01-11 00:38:46 +0000190 return Owned(SubStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 }
Sebastian Redlde307472009-01-11 00:38:46 +0000192
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 // Otherwise, this label was forward declared, and we just found its real
194 // definition. Fill in the forward definition and return it.
195 LabelDecl->setIdentLoc(IdentLoc);
Chris Lattner0fa152e2007-07-21 03:00:26 +0000196 LabelDecl->setSubStmt(SubStmt);
Sebastian Redlde307472009-01-11 00:38:46 +0000197 return Owned(LabelDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
Sebastian Redlde307472009-01-11 00:38:46 +0000200Action::OwningStmtResult
Anders Carlssona99fad82009-05-17 18:26:53 +0000201Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal,
Sebastian Redlde307472009-01-11 00:38:46 +0000202 StmtArg ThenVal, SourceLocation ElseLoc,
203 StmtArg ElseVal) {
Anders Carlssona99fad82009-05-17 18:26:53 +0000204 OwningExprResult CondResult(CondVal.release());
205
206 Expr *condExpr = CondResult.takeAs<Expr>();
Sebastian Redlde307472009-01-11 00:38:46 +0000207
Steve Naroff1b273c42007-09-16 14:56:35 +0000208 assert(condExpr && "ActOnIfStmt(): missing expression");
Sebastian Redlde307472009-01-11 00:38:46 +0000209
Douglas Gregord06f6ca2009-05-15 18:53:42 +0000210 if (!condExpr->isTypeDependent()) {
211 DefaultFunctionArrayConversion(condExpr);
212 // Take ownership again until we're past the error checking.
Anders Carlssona99fad82009-05-17 18:26:53 +0000213 CondResult = condExpr;
Douglas Gregord06f6ca2009-05-15 18:53:42 +0000214 QualType condType = condExpr->getType();
215
216 if (getLangOptions().CPlusPlus) {
217 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
218 return StmtError();
219 } else if (!condType->isScalarType()) // C99 6.8.4.1p1
220 return StmtError(Diag(IfLoc,
221 diag::err_typecheck_statement_requires_scalar)
222 << condType << condExpr->getSourceRange());
223 }
Sebastian Redlde307472009-01-11 00:38:46 +0000224
Anders Carlssone9146f22009-05-01 19:49:17 +0000225 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
Anders Carlsson75443112009-07-30 22:39:03 +0000226 DiagnoseUnusedExprResult(thenStmt);
Reid Spencer5f016e22007-07-11 17:01:13 +0000227
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000228 // Warn if the if block has a null body without an else value.
229 // this helps prevent bugs due to typos, such as
230 // if (condition);
231 // do_stuff();
Sebastian Redlde307472009-01-11 00:38:46 +0000232 if (!ElseVal.get()) {
Anders Carlsson2d85f8b2007-10-10 20:50:11 +0000233 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
234 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
235 }
236
Anders Carlsson75443112009-07-30 22:39:03 +0000237 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
238 DiagnoseUnusedExprResult(elseStmt);
239
Anders Carlssona99fad82009-05-17 18:26:53 +0000240 CondResult.release();
Ted Kremenek8189cde2009-02-07 01:47:29 +0000241 return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt,
Anders Carlsson75443112009-07-30 22:39:03 +0000242 ElseLoc, elseStmt));
Reid Spencer5f016e22007-07-11 17:01:13 +0000243}
244
Sebastian Redlde307472009-01-11 00:38:46 +0000245Action::OwningStmtResult
246Sema::ActOnStartOfSwitchStmt(ExprArg cond) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000247 Expr *Cond = cond.takeAs<Expr>();
Sebastian Redlde307472009-01-11 00:38:46 +0000248
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000249 if (getLangOptions().CPlusPlus) {
250 // C++ 6.4.2.p2:
251 // The condition shall be of integral type, enumeration type, or of a class
252 // type for which a single conversion function to integral or enumeration
253 // type exists (12.3). If the condition is of class type, the condition is
254 // converted by calling that conversion function, and the result of the
255 // conversion is used in place of the original condition for the remainder
256 // of this section. Integral promotions are performed.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000257 if (!Cond->isTypeDependent()) {
258 QualType Ty = Cond->getType();
259
260 // FIXME: Handle class types.
261
262 // If the type is wrong a diagnostic will be emitted later at
263 // ActOnFinishSwitchStmt.
264 if (Ty->isIntegralType() || Ty->isEnumeralType()) {
265 // Integral promotions are performed.
266 // FIXME: Integral promotions for C++ are not complete.
267 UsualUnaryConversions(Cond);
268 }
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000269 }
270 } else {
271 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
272 UsualUnaryConversions(Cond);
273 }
Sebastian Redlde307472009-01-11 00:38:46 +0000274
Ted Kremenek8189cde2009-02-07 01:47:29 +0000275 SwitchStmt *SS = new (Context) SwitchStmt(Cond);
Chris Lattnerbcfce662009-04-18 20:10:59 +0000276 getSwitchStack().push_back(SS);
Sebastian Redlde307472009-01-11 00:38:46 +0000277 return Owned(SS);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000278}
Chris Lattner6c36be52007-07-18 02:28:47 +0000279
Chris Lattnerf4021e72007-08-23 05:46:52 +0000280/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
281/// the specified width and sign. If an overflow occurs, detect it and emit
282/// the specified diagnostic.
283void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
284 unsigned NewWidth, bool NewSign,
285 SourceLocation Loc,
286 unsigned DiagID) {
287 // Perform a conversion to the promoted condition type if needed.
288 if (NewWidth > Val.getBitWidth()) {
289 // If this is an extension, just do it.
290 llvm::APSInt OldVal(Val);
291 Val.extend(NewWidth);
292
293 // If the input was signed and negative and the output is unsigned,
294 // warn.
295 if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000296 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000297
298 Val.setIsSigned(NewSign);
299 } else if (NewWidth < Val.getBitWidth()) {
300 // If this is a truncation, check for overflow.
301 llvm::APSInt ConvVal(Val);
302 ConvVal.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000303 ConvVal.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000304 ConvVal.extend(Val.getBitWidth());
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000305 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerf4021e72007-08-23 05:46:52 +0000306 if (ConvVal != Val)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000307 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000308
309 // Regardless of whether a diagnostic was emitted, really do the
310 // truncation.
311 Val.trunc(NewWidth);
Chris Lattnerb2137ae2007-08-23 22:08:35 +0000312 Val.setIsSigned(NewSign);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000313 } else if (NewSign != Val.isSigned()) {
314 // Convert the sign to match the sign of the condition. This can cause
315 // overflow as well: unsigned(INTMIN)
316 llvm::APSInt OldVal(Val);
317 Val.setIsSigned(NewSign);
318
319 if (Val.isNegative()) // Sign bit changes meaning.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000320 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000321 }
322}
323
Chris Lattner0471f5b2007-08-23 18:29:20 +0000324namespace {
325 struct CaseCompareFunctor {
326 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
327 const llvm::APSInt &RHS) {
328 return LHS.first < RHS;
329 }
Chris Lattner0e85a272007-09-03 18:31:57 +0000330 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
331 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
332 return LHS.first < RHS.first;
333 }
Chris Lattner0471f5b2007-08-23 18:29:20 +0000334 bool operator()(const llvm::APSInt &LHS,
335 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
336 return LHS < RHS.first;
337 }
338 };
339}
340
Chris Lattner764a7ce2007-09-21 18:15:22 +0000341/// CmpCaseVals - Comparison predicate for sorting case values.
342///
343static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
344 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
345 if (lhs.first < rhs.first)
346 return true;
347
348 if (lhs.first == rhs.first &&
349 lhs.second->getCaseLoc().getRawEncoding()
350 < rhs.second->getCaseLoc().getRawEncoding())
351 return true;
352 return false;
353}
354
Sebastian Redlde307472009-01-11 00:38:46 +0000355Action::OwningStmtResult
356Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
357 StmtArg Body) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000358 Stmt *BodyStmt = Body.takeAs<Stmt>();
Sebastian Redlde307472009-01-11 00:38:46 +0000359
Chris Lattnerbcfce662009-04-18 20:10:59 +0000360 SwitchStmt *SS = getSwitchStack().back();
Sebastian Redlde307472009-01-11 00:38:46 +0000361 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
362
Steve Naroff9dcbfa42007-09-01 21:08:38 +0000363 SS->setBody(BodyStmt, SwitchLoc);
Chris Lattnerbcfce662009-04-18 20:10:59 +0000364 getSwitchStack().pop_back();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000365
Chris Lattnerf4021e72007-08-23 05:46:52 +0000366 Expr *CondExpr = SS->getCond();
367 QualType CondType = CondExpr->getType();
Sebastian Redlde307472009-01-11 00:38:46 +0000368
Douglas Gregordbb26db2009-05-15 23:57:33 +0000369 if (!CondExpr->isTypeDependent() &&
370 !CondType->isIntegerType()) { // C99 6.8.4.2p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000371 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000372 << CondType << CondExpr->getSourceRange();
Sebastian Redlde307472009-01-11 00:38:46 +0000373 return StmtError();
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000374 }
Sebastian Redlde307472009-01-11 00:38:46 +0000375
Chris Lattnerf4021e72007-08-23 05:46:52 +0000376 // Get the bitwidth of the switched-on value before promotions. We must
377 // convert the integer case values to this width before comparison.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000378 bool HasDependentValue
379 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
380 unsigned CondWidth
381 = HasDependentValue? 0
382 : static_cast<unsigned>(Context.getTypeSize(CondType));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000383 bool CondIsSigned = CondType->isSignedIntegerType();
384
385 // Accumulate all of the case values in a vector so that we can sort them
386 // and detect duplicates. This vector contains the APInt for the case after
387 // it has been converted to the condition type.
Chris Lattner0471f5b2007-08-23 18:29:20 +0000388 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
389 CaseValsTy CaseVals;
Chris Lattnerf4021e72007-08-23 05:46:52 +0000390
391 // Keep track of any GNU case ranges we see. The APSInt is the low value.
392 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
393
394 DefaultStmt *TheDefaultStmt = 0;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000395
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000396 bool CaseListIsErroneous = false;
397
Douglas Gregordbb26db2009-05-15 23:57:33 +0000398 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000399 SC = SC->getNextSwitchCase()) {
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000400
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000401 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerf4021e72007-08-23 05:46:52 +0000402 if (TheDefaultStmt) {
403 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner5f4a6822008-11-23 23:12:31 +0000404 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redlde307472009-01-11 00:38:46 +0000405
Chris Lattnerf4021e72007-08-23 05:46:52 +0000406 // FIXME: Remove the default statement from the switch block so that
Mike Stump390b4cc2009-05-16 07:39:55 +0000407 // we'll return a valid AST. This requires recursing down the AST and
408 // finding it, not something we are set up to do right now. For now,
409 // just lop the entire switch stmt out of the AST.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000410 CaseListIsErroneous = true;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000411 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000412 TheDefaultStmt = DS;
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000413
Chris Lattnerf4021e72007-08-23 05:46:52 +0000414 } else {
415 CaseStmt *CS = cast<CaseStmt>(SC);
416
417 // We already verified that the expression has a i-c-e value (C99
418 // 6.8.4.2p3) - get that value now.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000419 Expr *Lo = CS->getLHS();
Douglas Gregordbb26db2009-05-15 23:57:33 +0000420
421 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
422 HasDependentValue = true;
423 break;
424 }
425
Anders Carlsson51fe9962008-11-22 21:04:56 +0000426 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
Chris Lattnerf4021e72007-08-23 05:46:52 +0000427
428 // Convert the value to the same width/sign as the condition.
429 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
430 CS->getLHS()->getLocStart(),
431 diag::warn_case_value_overflow);
Anders Carlssonc1fcb772007-07-22 07:07:56 +0000432
Chris Lattner1e0a3902008-01-16 19:17:22 +0000433 // If the LHS is not the same type as the condition, insert an implicit
434 // cast.
435 ImpCastExprToType(Lo, CondType);
436 CS->setLHS(Lo);
437
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000438 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000439 if (CS->getRHS()) {
440 if (CS->getRHS()->isTypeDependent() ||
441 CS->getRHS()->isValueDependent()) {
442 HasDependentValue = true;
443 break;
444 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000445 CaseRanges.push_back(std::make_pair(LoVal, CS));
Douglas Gregordbb26db2009-05-15 23:57:33 +0000446 } else
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000447 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerf4021e72007-08-23 05:46:52 +0000448 }
449 }
Douglas Gregordbb26db2009-05-15 23:57:33 +0000450
451 if (!HasDependentValue) {
452 // Sort all the scalar case values so we can easily detect duplicates.
453 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
454
455 if (!CaseVals.empty()) {
456 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
457 if (CaseVals[i].first == CaseVals[i+1].first) {
458 // If we have a duplicate, report it.
459 Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
460 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
461 Diag(CaseVals[i].second->getLHS()->getLocStart(),
462 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000463 // FIXME: We really want to remove the bogus case stmt from the
464 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000465 CaseListIsErroneous = true;
466 }
467 }
468 }
Chris Lattnerf4021e72007-08-23 05:46:52 +0000469
Douglas Gregordbb26db2009-05-15 23:57:33 +0000470 // Detect duplicate case ranges, which usually don't exist at all in
471 // the first place.
472 if (!CaseRanges.empty()) {
473 // Sort all the case ranges by their low value so we can easily detect
474 // overlaps between ranges.
475 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
476
477 // Scan the ranges, computing the high values and removing empty ranges.
478 std::vector<llvm::APSInt> HiVals;
479 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
480 CaseStmt *CR = CaseRanges[i].second;
481 Expr *Hi = CR->getRHS();
482 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
483
484 // Convert the value to the same width/sign as the condition.
485 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
486 CR->getRHS()->getLocStart(),
487 diag::warn_case_value_overflow);
488
489 // If the LHS is not the same type as the condition, insert an implicit
490 // cast.
491 ImpCastExprToType(Hi, CondType);
492 CR->setRHS(Hi);
493
494 // If the low value is bigger than the high value, the case is empty.
495 if (CaseRanges[i].first > HiVal) {
496 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
497 << SourceRange(CR->getLHS()->getLocStart(),
498 CR->getRHS()->getLocEnd());
499 CaseRanges.erase(CaseRanges.begin()+i);
500 --i, --e;
501 continue;
502 }
503 HiVals.push_back(HiVal);
504 }
505
506 // Rescan the ranges, looking for overlap with singleton values and other
507 // ranges. Since the range list is sorted, we only need to compare case
508 // ranges with their neighbors.
509 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
510 llvm::APSInt &CRLo = CaseRanges[i].first;
511 llvm::APSInt &CRHi = HiVals[i];
512 CaseStmt *CR = CaseRanges[i].second;
513
514 // Check to see whether the case range overlaps with any
515 // singleton cases.
516 CaseStmt *OverlapStmt = 0;
517 llvm::APSInt OverlapVal(32);
518
519 // Find the smallest value >= the lower bound. If I is in the
520 // case range, then we have overlap.
521 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
522 CaseVals.end(), CRLo,
523 CaseCompareFunctor());
524 if (I != CaseVals.end() && I->first < CRHi) {
525 OverlapVal = I->first; // Found overlap with scalar.
526 OverlapStmt = I->second;
527 }
528
529 // Find the smallest value bigger than the upper bound.
530 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
531 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
532 OverlapVal = (I-1)->first; // Found overlap with scalar.
533 OverlapStmt = (I-1)->second;
534 }
535
536 // Check to see if this case stmt overlaps with the subsequent
537 // case range.
538 if (i && CRLo <= HiVals[i-1]) {
539 OverlapVal = HiVals[i-1]; // Found overlap with range.
540 OverlapStmt = CaseRanges[i-1].second;
541 }
542
543 if (OverlapStmt) {
544 // If we have a duplicate, report it.
545 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
546 << OverlapVal.toString(10);
547 Diag(OverlapStmt->getLHS()->getLocStart(),
548 diag::note_duplicate_case_prev);
Mike Stump390b4cc2009-05-16 07:39:55 +0000549 // FIXME: We really want to remove the bogus case stmt from the
550 // substmt, but we have no way to do this right now.
Douglas Gregordbb26db2009-05-15 23:57:33 +0000551 CaseListIsErroneous = true;
552 }
Chris Lattnerf3348502007-08-23 14:29:07 +0000553 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000554 }
555 }
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000556
Mike Stump390b4cc2009-05-16 07:39:55 +0000557 // FIXME: If the case list was broken is some way, we don't have a good system
558 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattnerb2ec9d62007-08-23 06:23:56 +0000559 if (CaseListIsErroneous)
Sebastian Redlde307472009-01-11 00:38:46 +0000560 return StmtError();
561
562 Switch.release();
563 return Owned(SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000564}
565
Sebastian Redlf05b1522009-01-16 23:28:06 +0000566Action::OwningStmtResult
Anders Carlsson7f537c12009-05-17 21:22:26 +0000567Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) {
568 ExprArg CondArg(Cond.release());
569 Expr *condExpr = CondArg.takeAs<Expr>();
Steve Naroff1b273c42007-09-16 14:56:35 +0000570 assert(condExpr && "ActOnWhileStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +0000571
Douglas Gregor4a2e2042009-05-15 21:45:53 +0000572 if (!condExpr->isTypeDependent()) {
573 DefaultFunctionArrayConversion(condExpr);
Anders Carlsson7f537c12009-05-17 21:22:26 +0000574 CondArg = condExpr;
Douglas Gregor4a2e2042009-05-15 21:45:53 +0000575 QualType condType = condExpr->getType();
576
577 if (getLangOptions().CPlusPlus) {
578 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
579 return StmtError();
580 } else if (!condType->isScalarType()) // C99 6.8.5p2
581 return StmtError(Diag(WhileLoc,
582 diag::err_typecheck_statement_requires_scalar)
583 << condType << condExpr->getSourceRange());
584 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Anders Carlsson75443112009-07-30 22:39:03 +0000586 Stmt *bodyStmt = Body.takeAs<Stmt>();
587 DiagnoseUnusedExprResult(bodyStmt);
588
Anders Carlsson7f537c12009-05-17 21:22:26 +0000589 CondArg.release();
Anders Carlsson75443112009-07-30 22:39:03 +0000590 return Owned(new (Context) WhileStmt(condExpr, bodyStmt, WhileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000591}
592
Sebastian Redlf05b1522009-01-16 23:28:06 +0000593Action::OwningStmtResult
594Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
Chris Lattner98913592009-06-12 23:04:47 +0000595 SourceLocation WhileLoc, SourceLocation CondLParen,
596 ExprArg Cond, SourceLocation CondRParen) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000597 Expr *condExpr = Cond.takeAs<Expr>();
Steve Naroff1b273c42007-09-16 14:56:35 +0000598 assert(condExpr && "ActOnDoStmt(): missing expression");
Sebastian Redlf05b1522009-01-16 23:28:06 +0000599
Douglas Gregor9f3ca2a2009-05-15 21:56:04 +0000600 if (!condExpr->isTypeDependent()) {
601 DefaultFunctionArrayConversion(condExpr);
602 Cond = condExpr;
603 QualType condType = condExpr->getType();
604
605 if (getLangOptions().CPlusPlus) {
606 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
607 return StmtError();
608 } else if (!condType->isScalarType()) // C99 6.8.5p2
609 return StmtError(Diag(DoLoc,
610 diag::err_typecheck_statement_requires_scalar)
611 << condType << condExpr->getSourceRange());
612 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000613
Anders Carlsson75443112009-07-30 22:39:03 +0000614 Stmt *bodyStmt = Body.takeAs<Stmt>();
615 DiagnoseUnusedExprResult(bodyStmt);
616
Sebastian Redlf05b1522009-01-16 23:28:06 +0000617 Cond.release();
Anders Carlsson75443112009-07-30 22:39:03 +0000618 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
Chris Lattner98913592009-06-12 23:04:47 +0000619 WhileLoc, CondRParen));
Reid Spencer5f016e22007-07-11 17:01:13 +0000620}
621
Sebastian Redlf05b1522009-01-16 23:28:06 +0000622Action::OwningStmtResult
623Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
624 StmtArg first, ExprArg second, ExprArg third,
625 SourceLocation RParenLoc, StmtArg body) {
626 Stmt *First = static_cast<Stmt*>(first.get());
627 Expr *Second = static_cast<Expr*>(second.get());
628 Expr *Third = static_cast<Expr*>(third.get());
629 Stmt *Body = static_cast<Stmt*>(body.get());
630
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000631 if (!getLangOptions().CPlusPlus) {
632 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000633 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
634 // declare identifiers for objects having storage class 'auto' or
635 // 'register'.
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000636 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
637 DI!=DE; ++DI) {
638 VarDecl *VD = dyn_cast<VarDecl>(*DI);
639 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
640 VD = 0;
641 if (VD == 0)
642 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
643 // FIXME: mark decl erroneous!
644 }
Chris Lattnerae3b7012007-08-28 05:03:08 +0000645 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 }
Douglas Gregor5831c6a2009-05-15 22:12:32 +0000647 if (Second && !Second->isTypeDependent()) {
Chris Lattner36c4b0e2007-08-28 04:55:47 +0000648 DefaultFunctionArrayConversion(Second);
649 QualType SecondType = Second->getType();
Sebastian Redlf05b1522009-01-16 23:28:06 +0000650
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000651 if (getLangOptions().CPlusPlus) {
652 if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4
Sebastian Redlf05b1522009-01-16 23:28:06 +0000653 return StmtError();
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000654 } else if (!SecondType->isScalarType()) // C99 6.8.5p2
Sebastian Redlf05b1522009-01-16 23:28:06 +0000655 return StmtError(Diag(ForLoc,
656 diag::err_typecheck_statement_requires_scalar)
657 << SecondType << Second->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 }
Anders Carlsson75443112009-07-30 22:39:03 +0000659
Anders Carlsson3af708f2009-08-01 01:39:59 +0000660 DiagnoseUnusedExprResult(First);
661 DiagnoseUnusedExprResult(Third);
Anders Carlsson75443112009-07-30 22:39:03 +0000662 DiagnoseUnusedExprResult(Body);
663
Sebastian Redlf05b1522009-01-16 23:28:06 +0000664 first.release();
665 second.release();
666 third.release();
667 body.release();
Douglas Gregor5831c6a2009-05-15 22:12:32 +0000668 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc,
669 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000670}
671
Sebastian Redlf05b1522009-01-16 23:28:06 +0000672Action::OwningStmtResult
673Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
674 SourceLocation LParenLoc,
675 StmtArg first, ExprArg second,
676 SourceLocation RParenLoc, StmtArg body) {
677 Stmt *First = static_cast<Stmt*>(first.get());
678 Expr *Second = static_cast<Expr*>(second.get());
679 Stmt *Body = static_cast<Stmt*>(body.get());
Fariborz Jahanian20552d22008-01-10 20:33:58 +0000680 if (First) {
681 QualType FirstType;
682 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner7e24e822009-03-28 06:33:19 +0000683 if (!DS->isSingleDecl())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000684 return StmtError(Diag((*DS->decl_begin())->getLocation(),
685 diag::err_toomany_element_decls));
686
Chris Lattner7e24e822009-03-28 06:33:19 +0000687 Decl *D = DS->getSingleDecl();
Ted Kremenekf34afee2008-10-06 20:58:11 +0000688 FirstType = cast<ValueDecl>(D)->getType();
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000689 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
690 // declare identifiers for objects having storage class 'auto' or
691 // 'register'.
Steve Naroff248a7532008-04-15 22:42:06 +0000692 VarDecl *VD = cast<VarDecl>(D);
693 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
Sebastian Redlf05b1522009-01-16 23:28:06 +0000694 return StmtError(Diag(VD->getLocation(),
695 diag::err_non_variable_decl_in_for));
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000696 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000697 if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
Sebastian Redlf05b1522009-01-16 23:28:06 +0000698 return StmtError(Diag(First->getLocStart(),
699 diag::err_selector_element_not_lvalue)
700 << First->getSourceRange());
701
702 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1fe379f2008-08-25 18:16:36 +0000703 }
Fariborz Jahaniana5e42a82009-08-14 21:53:27 +0000704 if (!FirstType->isObjCObjectPointerType() &&
705 !FirstType->isBlockPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000706 Diag(ForLoc, diag::err_selector_element_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000707 << FirstType << First->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000708 }
709 if (Second) {
710 DefaultFunctionArrayConversion(Second);
711 QualType SecondType = Second->getType();
Steve Narofff4954562009-07-16 15:41:00 +0000712 if (!SecondType->isObjCObjectPointerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000713 Diag(ForLoc, diag::err_collection_expr_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000714 << SecondType << Second->getSourceRange();
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000715 }
Sebastian Redlf05b1522009-01-16 23:28:06 +0000716 first.release();
717 second.release();
718 body.release();
Ted Kremenek8189cde2009-02-07 01:47:29 +0000719 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
720 ForLoc, RParenLoc));
Fariborz Jahanian3ba5a0f2008-01-03 17:55:25 +0000721}
Reid Spencer5f016e22007-07-11 17:01:13 +0000722
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000723Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000724Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 IdentifierInfo *LabelII) {
Steve Naroff4eb206b2008-09-03 18:15:37 +0000726 // If we are in a block, reject all gotos for now.
727 if (CurBlock)
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000728 return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
Steve Naroff4eb206b2008-09-03 18:15:37 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +0000731 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Reid Spencer5f016e22007-07-11 17:01:13 +0000732
Steve Naroffcaaacec2009-03-13 15:38:40 +0000733 // If we haven't seen this label yet, create a forward reference.
734 if (LabelDecl == 0)
Ted Kremenek8189cde2009-02-07 01:47:29 +0000735 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000736
Ted Kremenek8189cde2009-02-07 01:47:29 +0000737 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000738}
739
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000740Action::OwningStmtResult
Chris Lattnerad56d682009-04-19 01:04:21 +0000741Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000742 ExprArg DestExp) {
Eli Friedmanbbf46232009-03-26 00:18:06 +0000743 // Convert operand to void*
Eli Friedman33083822009-03-26 07:32:37 +0000744 Expr* E = DestExp.takeAs<Expr>();
Douglas Gregor5f1b9e62009-05-16 00:20:29 +0000745 if (!E->isTypeDependent()) {
746 QualType ETy = E->getType();
747 AssignConvertType ConvTy =
748 CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
749 if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
750 E, "passing"))
751 return StmtError();
752 }
753 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000754}
755
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000756Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000757Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 Scope *S = CurScope->getContinueParent();
759 if (!S) {
760 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000761 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000763
Ted Kremenek8189cde2009-02-07 01:47:29 +0000764 return Owned(new (Context) ContinueStmt(ContinueLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000765}
766
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000767Action::OwningStmtResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000768Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 Scope *S = CurScope->getBreakParent();
770 if (!S) {
771 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000772 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000774
Ted Kremenek8189cde2009-02-07 01:47:29 +0000775 return Owned(new (Context) BreakStmt(BreakLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000776}
777
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000778/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
Steve Naroff4eb206b2008-09-03 18:15:37 +0000779///
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000780Action::OwningStmtResult
Steve Naroff4eb206b2008-09-03 18:15:37 +0000781Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Steve Naroff4eb206b2008-09-03 18:15:37 +0000782 // If this is the first return we've seen in the block, infer the type of
783 // the block from it.
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +0000784 if (CurBlock->ReturnType.isNull()) {
Steve Naroffc50a4a52008-09-16 22:25:10 +0000785 if (RetValExp) {
Steve Naroff16564422008-09-24 22:26:48 +0000786 // Don't call UsualUnaryConversions(), since we don't want to do
787 // integer promotions here.
788 DefaultFunctionArrayConversion(RetValExp);
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +0000789 CurBlock->ReturnType = RetValExp->getType();
790 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
791 // We have to remove a 'const' added to copied-in variable which was
792 // part of the implementation spec. and not the actual qualifier for
793 // the variable.
794 if (CDRE->isConstQualAdded())
795 CurBlock->ReturnType.removeConst();
796 }
Steve Naroffc50a4a52008-09-16 22:25:10 +0000797 } else
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +0000798 CurBlock->ReturnType = Context.VoidTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +0000799 }
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +0000800 QualType FnRetType = CurBlock->ReturnType;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000801
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000802 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
Mike Stump6c92fa72009-04-29 21:40:37 +0000803 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
804 << getCurFunctionOrMethodDecl()->getDeclName();
805 return StmtError();
806 }
807
Steve Naroff4eb206b2008-09-03 18:15:37 +0000808 // Otherwise, verify that this result type matches the previous one. We are
809 // pickier with blocks than for normal functions because we don't have GCC
810 // compatibility to worry about here.
811 if (CurBlock->ReturnType->isVoidType()) {
812 if (RetValExp) {
813 Diag(ReturnLoc, diag::err_return_block_has_expr);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000814 RetValExp->Destroy(Context);
Steve Naroff4eb206b2008-09-03 18:15:37 +0000815 RetValExp = 0;
816 }
Ted Kremenek8189cde2009-02-07 01:47:29 +0000817 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroff4eb206b2008-09-03 18:15:37 +0000818 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000819
820 if (!RetValExp)
821 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
822
Mike Stump98eb8a72009-02-04 22:31:32 +0000823 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
824 // we have a non-void block with an expression, continue checking
825 QualType RetValType = RetValExp->getType();
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000826
Mike Stump98eb8a72009-02-04 22:31:32 +0000827 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
828 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
829 // function return.
830
831 // In C++ the return statement is handled via a copy initialization.
832 // the C version of which boils down to CheckSingleAssignmentConstraints.
833 // FIXME: Leaks RetValExp.
834 if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
835 return StmtError();
836
837 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroff4eb206b2008-09-03 18:15:37 +0000838 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000839
Ted Kremenek8189cde2009-02-07 01:47:29 +0000840 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Steve Naroff4eb206b2008-09-03 18:15:37 +0000841}
Reid Spencer5f016e22007-07-11 17:01:13 +0000842
Sebastian Redle2b68332009-04-12 17:16:29 +0000843/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
844/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
845static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
846 Expr *RetExpr) {
847 QualType ExprType = RetExpr->getType();
848 // - in a return statement in a function with ...
849 // ... a class return type ...
850 if (!RetType->isRecordType())
851 return false;
852 // ... the same cv-unqualified type as the function return type ...
853 if (Ctx.getCanonicalType(RetType).getUnqualifiedType() !=
854 Ctx.getCanonicalType(ExprType).getUnqualifiedType())
855 return false;
856 // ... the expression is the name of a non-volatile automatic object ...
857 // We ignore parentheses here.
858 // FIXME: Is this compliant?
859 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
860 if (!DR)
861 return false;
862 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
863 if (!VD)
864 return false;
865 return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
866 && !VD->getType().isVolatileQualified();
867}
868
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000869Action::OwningStmtResult
Anders Carlssonf53b4432009-08-18 16:11:00 +0000870Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
871 Expr *RetValExp = rex.takeAs<Expr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +0000872 if (CurBlock)
873 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000874
Chris Lattner371f2582008-12-04 23:50:19 +0000875 QualType FnRetType;
Mike Stumpf7c41da2009-04-29 00:43:21 +0000876 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner371f2582008-12-04 23:50:19 +0000877 FnRetType = FD->getResultType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000878 if (FD->hasAttr<NoReturnAttr>())
Chris Lattner86625872009-05-31 19:32:13 +0000879 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Mike Stumpf7c41da2009-04-29 00:43:21 +0000880 << getCurFunctionOrMethodDecl()->getDeclName();
Mike Stumpf7c41da2009-04-29 00:43:21 +0000881 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
Steve Naroffc97fb9a2009-03-03 00:45:38 +0000882 FnRetType = MD->getResultType();
883 else // If we don't have a function/method context, bail.
884 return StmtError();
885
Chris Lattner5cf216b2008-01-04 18:04:52 +0000886 if (FnRetType->isVoidType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000887 if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns)
Chris Lattner65ce04b2008-12-18 02:01:17 +0000888 unsigned D = diag::ext_return_has_expr;
889 if (RetValExp->getType()->isVoidType())
890 D = diag::ext_return_has_void_expr;
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000891
Chris Lattnere878eb02008-12-18 02:03:48 +0000892 // return (some void expression); is legal in C++.
893 if (D != diag::ext_return_has_void_expr ||
894 !getLangOptions().CPlusPlus) {
895 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
896 Diag(ReturnLoc, D)
897 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
898 << RetValExp->getSourceRange();
899 }
Anders Carlssonf53b4432009-08-18 16:11:00 +0000900
901 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 }
Ted Kremenek8189cde2009-02-07 01:47:29 +0000903 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000905
Anders Carlsson03d77762009-05-15 00:48:27 +0000906 if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000907 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
908 // C99 6.8.6.4p1 (ext_ since GCC warns)
909 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
910
911 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner08631c52008-11-23 21:45:46 +0000912 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner3c73c412008-11-19 08:23:25 +0000913 else
Chris Lattner08631c52008-11-23 21:45:46 +0000914 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000915 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
Chris Lattner3c73c412008-11-19 08:23:25 +0000916 }
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000917
Douglas Gregor898574e2008-12-05 23:32:09 +0000918 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
919 // we have a non-void function with an expression, continue checking
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000920
Douglas Gregor898574e2008-12-05 23:32:09 +0000921 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
922 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000923 // function return.
924
Sebastian Redle2b68332009-04-12 17:16:29 +0000925 // C++0x 12.8p15: When certain criteria are met, an implementation is
926 // allowed to omit the copy construction of a class object, [...]
927 // - in a return statement in a function with a class return type, when
928 // the expression is the name of a non-volatile automatic object with
929 // the same cv-unqualified type as the function return type, the copy
930 // operation can be omitted [...]
931 // C++0x 12.8p16: When the criteria for elision of a copy operation are met
932 // and the object to be copied is designated by an lvalue, overload
933 // resolution to select the constructor for the copy is first performed
934 // as if the object were designated by an rvalue.
935 // Note that we only compute Elidable if we're in C++0x, since we don't
936 // care otherwise.
937 bool Elidable = getLangOptions().CPlusPlus0x ?
938 IsReturnCopyElidable(Context, FnRetType, RetValExp) :
939 false;
940
Douglas Gregor898574e2008-12-05 23:32:09 +0000941 // In C++ the return statement is handled via a copy initialization.
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000942 // the C version of which boils down to CheckSingleAssignmentConstraints.
Sebastian Redle2b68332009-04-12 17:16:29 +0000943 // FIXME: Leaks RetValExp on error.
944 if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable))
Sebastian Redl4cffe2f2009-01-18 13:19:59 +0000945 return StmtError();
946
Douglas Gregor898574e2008-12-05 23:32:09 +0000947 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
948 }
949
Anders Carlssonf53b4432009-08-18 16:11:00 +0000950 if (RetValExp)
951 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000952 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
Reid Spencer5f016e22007-07-11 17:01:13 +0000953}
954
Chris Lattner810f6d52009-03-13 17:38:01 +0000955/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
956/// ignore "noop" casts in places where an lvalue is required by an inline asm.
957/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
958/// provide a strong guidance to not use it.
959///
960/// This method checks to see if the argument is an acceptable l-value and
961/// returns false if it is a case we can handle.
962static bool CheckAsmLValue(const Expr *E, Sema &S) {
963 if (E->isLvalue(S.Context) == Expr::LV_Valid)
964 return false; // Cool, this is an lvalue.
965
966 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
967 // are supposed to allow.
968 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
969 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
970 if (!S.getLangOptions().HeinousExtensions)
971 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
972 << E->getSourceRange();
973 else
974 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
975 << E->getSourceRange();
976 // Accept, even if we emitted an error diagnostic.
977 return false;
978 }
979
980 // None of the above, just randomly invalid non-lvalue.
981 return true;
982}
983
984
Sebastian Redl3037ed02009-01-18 16:53:17 +0000985Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
986 bool IsSimple,
987 bool IsVolatile,
988 unsigned NumOutputs,
989 unsigned NumInputs,
990 std::string *Names,
991 MultiExprArg constraints,
992 MultiExprArg exprs,
993 ExprArg asmString,
994 MultiExprArg clobbers,
995 SourceLocation RParenLoc) {
996 unsigned NumClobbers = clobbers.size();
997 StringLiteral **Constraints =
998 reinterpret_cast<StringLiteral**>(constraints.get());
999 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1000 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1001 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1002
Anders Carlsson03eb5432009-01-27 20:38:24 +00001003 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1004
Chris Lattner1708b962008-08-18 19:55:17 +00001005 // The parser verifies that there is a string literal here.
Chris Lattner6bc52112008-07-23 06:46:56 +00001006 if (AsmString->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001007 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1008 << AsmString->getSourceRange());
1009
Chris Lattner1708b962008-08-18 19:55:17 +00001010 for (unsigned i = 0; i != NumOutputs; i++) {
1011 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001012 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001013 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1014 << Literal->getSourceRange());
1015
Chris Lattner432c8692009-04-26 17:19:08 +00001016 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001017 Literal->getByteLength(),
1018 Names[i]);
Chris Lattner432c8692009-04-26 17:19:08 +00001019 if (!Context.Target.validateOutputConstraint(Info))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001020 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001021 diag::err_asm_invalid_output_constraint)
1022 << Info.getConstraintStr());
Sebastian Redl3037ed02009-01-18 16:53:17 +00001023
Anders Carlssond04c6e22007-11-27 04:11:28 +00001024 // Check that the output exprs are valid lvalues.
Eli Friedman72056a22009-05-03 07:49:42 +00001025 Expr *OutputExpr = Exprs[i];
Chris Lattner810f6d52009-03-13 17:38:01 +00001026 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman72056a22009-05-03 07:49:42 +00001027 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001028 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman72056a22009-05-03 07:49:42 +00001029 << OutputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001030 }
Anders Carlsson03eb5432009-01-27 20:38:24 +00001031
Chris Lattner44def072009-04-26 07:16:29 +00001032 OutputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001033 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001034
Chris Lattner806503f2009-05-03 05:55:43 +00001035 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1036
Anders Carlsson04728b72007-11-23 19:43:50 +00001037 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner1708b962008-08-18 19:55:17 +00001038 StringLiteral *Literal = Constraints[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001039 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001040 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1041 << Literal->getSourceRange());
1042
Chris Lattner432c8692009-04-26 17:19:08 +00001043 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001044 Literal->getByteLength(),
1045 Names[i]);
Jay Foadbeaaccd2009-05-21 09:52:38 +00001046 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001047 NumOutputs, Info)) {
Sebastian Redl3037ed02009-01-18 16:53:17 +00001048 return StmtError(Diag(Literal->getLocStart(),
Chris Lattner432c8692009-04-26 17:19:08 +00001049 diag::err_asm_invalid_input_constraint)
1050 << Info.getConstraintStr());
Anders Carlssond04c6e22007-11-27 04:11:28 +00001051 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001052
Eli Friedman72056a22009-05-03 07:49:42 +00001053 Expr *InputExpr = Exprs[i];
Sebastian Redl3037ed02009-01-18 16:53:17 +00001054
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001055 // Only allow void types for memory constraints.
Chris Lattner44def072009-04-26 07:16:29 +00001056 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattner810f6d52009-03-13 17:38:01 +00001057 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman72056a22009-05-03 07:49:42 +00001058 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001059 diag::err_asm_invalid_lvalue_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00001060 << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001061 << InputExpr->getSourceRange());
Anders Carlsson04728b72007-11-23 19:43:50 +00001062 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001063
Chris Lattner44def072009-04-26 07:16:29 +00001064 if (Info.allowsRegister()) {
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001065 if (InputExpr->getType()->isVoidType()) {
Eli Friedman72056a22009-05-03 07:49:42 +00001066 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001067 diag::err_asm_invalid_type_in_input)
Chris Lattner432c8692009-04-26 17:19:08 +00001068 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman72056a22009-05-03 07:49:42 +00001069 << InputExpr->getSourceRange());
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001070 }
Anders Carlssond9fca6e2009-01-20 20:49:22 +00001071 }
Anders Carlsson60329792009-02-22 02:11:23 +00001072
1073 DefaultFunctionArrayConversion(Exprs[i]);
Chris Lattner49ac8812009-04-26 18:22:24 +00001074
Chris Lattner806503f2009-05-03 05:55:43 +00001075 InputConstraintInfos.push_back(Info);
Anders Carlsson04728b72007-11-23 19:43:50 +00001076 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001077
Anders Carlsson6fa90862007-11-25 00:25:21 +00001078 // Check that the clobbers are valid.
Chris Lattner1708b962008-08-18 19:55:17 +00001079 for (unsigned i = 0; i != NumClobbers; i++) {
1080 StringLiteral *Literal = Clobbers[i];
Chris Lattner6bc52112008-07-23 06:46:56 +00001081 if (Literal->isWide())
Sebastian Redl3037ed02009-01-18 16:53:17 +00001082 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1083 << Literal->getSourceRange());
1084
Daniel Dunbar77659342009-08-19 20:04:03 +00001085 std::string Clobber(Literal->getStrData(),
1086 Literal->getStrData() +
1087 Literal->getByteLength());
Sebastian Redl3037ed02009-01-18 16:53:17 +00001088
Chris Lattner6bc52112008-07-23 06:46:56 +00001089 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
Sebastian Redl3037ed02009-01-18 16:53:17 +00001090 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar77659342009-08-19 20:04:03 +00001091 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson6fa90862007-11-25 00:25:21 +00001092 }
Sebastian Redl3037ed02009-01-18 16:53:17 +00001093
1094 constraints.release();
1095 exprs.release();
1096 asmString.release();
1097 clobbers.release();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001098 AsmStmt *NS =
1099 new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1100 Names, Constraints, Exprs, AsmString, NumClobbers,
1101 Clobbers, RParenLoc);
1102 // Validate the asm string, ensuring it makes sense given the operands we
1103 // have.
1104 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1105 unsigned DiagOffs;
1106 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner2ff0f422009-03-10 23:57:07 +00001107 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1108 << AsmString->getSourceRange();
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001109 DeleteStmt(NS);
1110 return StmtError();
1111 }
1112
Chris Lattner806503f2009-05-03 05:55:43 +00001113 // Validate tied input operands for type mismatches.
1114 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1115 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1116
1117 // If this is a tied constraint, verify that the output and input have
1118 // either exactly the same type, or that they are int/ptr operands with the
1119 // same size (int/long, int*/long, are ok etc).
1120 if (!Info.hasTiedOperand()) continue;
1121
1122 unsigned TiedTo = Info.getTiedOperand();
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001123 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001124 Expr *InputExpr = Exprs[i+NumOutputs];
Chris Lattner7adaa182009-05-03 05:59:17 +00001125 QualType InTy = InputExpr->getType();
1126 QualType OutTy = OutputExpr->getType();
1127 if (Context.hasSameType(InTy, OutTy))
Chris Lattner806503f2009-05-03 05:55:43 +00001128 continue; // All types can be tied to themselves.
1129
Chris Lattner7adaa182009-05-03 05:59:17 +00001130 // Int/ptr operands have some special cases that we allow.
1131 if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1132 (InTy->isIntegerType() || InTy->isPointerType())) {
1133
1134 // They are ok if they are the same size. Tying void* to int is ok if
1135 // they are the same size, for example. This also allows tying void* to
1136 // int*.
Chris Lattner3351f112009-05-03 08:32:32 +00001137 uint64_t OutSize = Context.getTypeSize(OutTy);
1138 uint64_t InSize = Context.getTypeSize(InTy);
1139 if (OutSize == InSize)
Chris Lattner806503f2009-05-03 05:55:43 +00001140 continue;
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001141
Chris Lattner3351f112009-05-03 08:32:32 +00001142 // If the smaller input/output operand is not mentioned in the asm string,
1143 // then we can promote it and the asm string won't notice. Check this
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001144 // case now.
Chris Lattner3351f112009-05-03 08:32:32 +00001145 bool SmallerValueMentioned = false;
Chris Lattner58bce892009-05-03 08:24:16 +00001146 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1147 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1148 if (!Piece.isOperand()) continue;
Chris Lattner3351f112009-05-03 08:32:32 +00001149
1150 // If this is a reference to the input and if the input was the smaller
1151 // one, then we have to reject this asm.
1152 if (Piece.getOperandNo() == i+NumOutputs) {
1153 if (InSize < OutSize) {
1154 SmallerValueMentioned = true;
1155 break;
1156 }
1157 }
1158
1159 // If this is a reference to the input and if the input was the smaller
1160 // one, then we have to reject this asm.
1161 if (Piece.getOperandNo() == TiedTo) {
1162 if (InSize > OutSize) {
1163 SmallerValueMentioned = true;
1164 break;
1165 }
1166 }
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001167 }
1168
Chris Lattner3351f112009-05-03 08:32:32 +00001169 // If the smaller value wasn't mentioned in the asm string, and if the
1170 // output was a register, just extend the shorter one to the size of the
1171 // larger one.
1172 if (!SmallerValueMentioned &&
Chris Lattnerf69fcae2009-05-03 07:04:21 +00001173 OutputConstraintInfos[TiedTo].allowsRegister())
1174 continue;
Chris Lattner806503f2009-05-03 05:55:43 +00001175 }
1176
Chris Lattnerc1f3b282009-05-03 06:50:40 +00001177 Diag(InputExpr->getLocStart(),
Chris Lattner806503f2009-05-03 05:55:43 +00001178 diag::err_asm_tying_incompatible_types)
Chris Lattner7adaa182009-05-03 05:59:17 +00001179 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner806503f2009-05-03 05:55:43 +00001180 << InputExpr->getSourceRange();
1181 DeleteStmt(NS);
1182 return StmtError();
1183 }
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001184
1185 return Owned(NS);
Chris Lattnerfe795952007-10-29 04:04:16 +00001186}
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001187
Sebastian Redl431e90e2009-01-18 17:43:11 +00001188Action::OwningStmtResult
1189Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001190 SourceLocation RParen, DeclPtrTy Parm,
Sebastian Redl431e90e2009-01-18 17:43:11 +00001191 StmtArg Body, StmtArg catchList) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001192 Stmt *CatchList = catchList.takeAs<Stmt>();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001193 ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
Steve Narofff50cb362009-03-03 20:59:06 +00001194
1195 // PVD == 0 implies @catch(...).
Steve Naroff9d40ee52009-03-03 21:16:54 +00001196 if (PVD) {
Chris Lattner93c49452009-04-12 23:26:56 +00001197 // If we already know the decl is invalid, reject it.
1198 if (PVD->isInvalidDecl())
1199 return StmtError();
1200
Steve Narofff4954562009-07-16 15:41:00 +00001201 if (!PVD->getType()->isObjCObjectPointerType())
Steve Naroff9d40ee52009-03-03 21:16:54 +00001202 return StmtError(Diag(PVD->getLocation(),
1203 diag::err_catch_param_not_objc_type));
1204 if (PVD->getType()->isObjCQualifiedIdType())
1205 return StmtError(Diag(PVD->getLocation(),
Steve Naroffd198aba2009-03-03 23:13:51 +00001206 diag::err_illegal_qualifiers_on_catch_parm));
Steve Naroff9d40ee52009-03-03 21:16:54 +00001207 }
Chris Lattner93c49452009-04-12 23:26:56 +00001208
Ted Kremenek8189cde2009-02-07 01:47:29 +00001209 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
Anders Carlssone9146f22009-05-01 19:49:17 +00001210 PVD, Body.takeAs<Stmt>(), CatchList);
Sebastian Redl431e90e2009-01-18 17:43:11 +00001211 return Owned(CatchList ? CatchList : CS);
Fariborz Jahanian3b1191d2007-11-01 23:59:59 +00001212}
1213
Sebastian Redl431e90e2009-01-18 17:43:11 +00001214Action::OwningStmtResult
1215Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001216 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1217 static_cast<Stmt*>(Body.release())));
Fariborz Jahanian161a9c52007-11-02 00:18:53 +00001218}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001219
Sebastian Redl431e90e2009-01-18 17:43:11 +00001220Action::OwningStmtResult
1221Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1222 StmtArg Try, StmtArg Catch, StmtArg Finally) {
Chris Lattner38c5ebd2009-04-19 05:21:20 +00001223 CurFunctionNeedsScopeChecking = true;
Anders Carlssone9146f22009-05-01 19:49:17 +00001224 return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1225 Catch.takeAs<Stmt>(),
1226 Finally.takeAs<Stmt>()));
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001227}
1228
Sebastian Redl431e90e2009-01-18 17:43:11 +00001229Action::OwningStmtResult
Steve Naroff3dcfe102009-02-12 15:54:59 +00001230Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001231 Expr *ThrowExpr = expr.takeAs<Expr>();
Steve Naroff7151bbb2009-02-11 17:45:08 +00001232 if (!ThrowExpr) {
Steve Naroffe21dd6f2009-02-11 20:05:44 +00001233 // @throw without an expression designates a rethrow (which much occur
1234 // in the context of an @catch clause).
1235 Scope *AtCatchParent = CurScope;
1236 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1237 AtCatchParent = AtCatchParent->getParent();
1238 if (!AtCatchParent)
Steve Naroff4ab24142009-02-12 18:09:32 +00001239 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
Steve Naroff7151bbb2009-02-11 17:45:08 +00001240 } else {
1241 QualType ThrowType = ThrowExpr->getType();
1242 // Make sure the expression type is an ObjC pointer or "void *".
Steve Narofff4954562009-07-16 15:41:00 +00001243 if (!ThrowType->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001244 const PointerType *PT = ThrowType->getAs<PointerType>();
Steve Naroff7151bbb2009-02-11 17:45:08 +00001245 if (!PT || !PT->getPointeeType()->isVoidType())
Steve Naroff4ab24142009-02-12 18:09:32 +00001246 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1247 << ThrowExpr->getType() << ThrowExpr->getSourceRange());
Steve Naroff7151bbb2009-02-11 17:45:08 +00001248 }
1249 }
1250 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
Fariborz Jahanian39f8f152007-11-07 02:00:49 +00001251}
Fariborz Jahanianbd49a642007-11-02 15:39:31 +00001252
Sebastian Redl431e90e2009-01-18 17:43:11 +00001253Action::OwningStmtResult
1254Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1255 StmtArg SynchBody) {
Chris Lattner46c3c4b2009-04-21 06:01:00 +00001256 CurFunctionNeedsScopeChecking = true;
1257
Chris Lattnera868a202009-04-21 06:11:25 +00001258 // Make sure the expression type is an ObjC pointer or "void *".
1259 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
Steve Narofff4954562009-07-16 15:41:00 +00001260 if (!SyncExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001261 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
Chris Lattnera868a202009-04-21 06:11:25 +00001262 if (!PT || !PT->getPointeeType()->isVoidType())
1263 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1264 << SyncExpr->getType() << SyncExpr->getSourceRange());
1265 }
1266
Anders Carlssone9146f22009-05-01 19:49:17 +00001267 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1268 SynchExpr.takeAs<Stmt>(),
1269 SynchBody.takeAs<Stmt>()));
Fariborz Jahanianfa3ee8e2008-01-29 19:14:59 +00001270}
Sebastian Redl4b07b292008-12-22 19:15:10 +00001271
1272/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1273/// and creates a proper catch handler from them.
1274Action::OwningStmtResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001275Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
Sebastian Redl4b07b292008-12-22 19:15:10 +00001276 StmtArg HandlerBlock) {
1277 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001278 return Owned(new (Context) CXXCatchStmt(CatchLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001279 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
Anders Carlssone9146f22009-05-01 19:49:17 +00001280 HandlerBlock.takeAs<Stmt>()));
Sebastian Redl4b07b292008-12-22 19:15:10 +00001281}
Sebastian Redl8351da02008-12-22 21:35:02 +00001282
Sebastian Redlc447aba2009-07-29 17:15:45 +00001283class TypeWithHandler {
1284 QualType t;
1285 CXXCatchStmt *stmt;
1286public:
1287 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1288 : t(type), stmt(statement) {}
1289
1290 bool operator<(const TypeWithHandler &y) const {
1291 if (t.getTypePtr() < y.t.getTypePtr())
1292 return true;
1293 else if (t.getTypePtr() > y.t.getTypePtr())
1294 return false;
1295 else if (t.getCVRQualifiers() < y.t.getCVRQualifiers())
1296 return true;
1297 else if (t.getCVRQualifiers() < y.t.getCVRQualifiers())
1298 return false;
1299 else
1300 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1301 }
1302
1303 bool operator==(const TypeWithHandler& other) const {
1304 return t.getTypePtr() == other.t.getTypePtr()
1305 && t.getCVRQualifiers() == other.t.getCVRQualifiers();
1306 }
1307
1308 QualType getQualType() const { return t; }
1309 CXXCatchStmt *getCatchStmt() const { return stmt; }
1310 SourceLocation getTypeSpecStartLoc() const {
1311 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1312 }
1313};
1314
Sebastian Redl8351da02008-12-22 21:35:02 +00001315/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1316/// handlers and creates a try statement from them.
1317Action::OwningStmtResult
1318Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1319 MultiStmtArg RawHandlers) {
1320 unsigned NumHandlers = RawHandlers.size();
1321 assert(NumHandlers > 0 &&
1322 "The parser shouldn't call this if there are no handlers.");
1323 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1324
Sebastian Redlc447aba2009-07-29 17:15:45 +00001325 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1326
1327 for(unsigned i = 0; i < NumHandlers; ++i) {
Sebastian Redl8351da02008-12-22 21:35:02 +00001328 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redlc447aba2009-07-29 17:15:45 +00001329 if (!Handler->getExceptionDecl()) {
1330 if (i < NumHandlers - 1)
1331 return StmtError(Diag(Handler->getLocStart(),
1332 diag::err_early_catch_all));
1333
1334 continue;
1335 }
1336
1337 const QualType CaughtType = Handler->getCaughtType();
1338 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1339 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl8351da02008-12-22 21:35:02 +00001340 }
Sebastian Redlc447aba2009-07-29 17:15:45 +00001341
1342 // Detect handlers for the same type as an earlier one.
1343 if (NumHandlers > 1) {
1344 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1345
1346 TypeWithHandler prev = TypesWithHandlers[0];
1347 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1348 TypeWithHandler curr = TypesWithHandlers[i];
1349
1350 if (curr == prev) {
1351 Diag(curr.getTypeSpecStartLoc(),
1352 diag::warn_exception_caught_by_earlier_handler)
1353 << curr.getCatchStmt()->getCaughtType().getAsString();
1354 Diag(prev.getTypeSpecStartLoc(),
1355 diag::note_previous_exception_handler)
1356 << prev.getCatchStmt()->getCaughtType().getAsString();
1357 }
1358
1359 prev = curr;
1360 }
1361 }
1362
Sebastian Redl8351da02008-12-22 21:35:02 +00001363 // FIXME: We should detect handlers that cannot catch anything because an
1364 // earlier handler catches a superclass. Need to find a method that is not
1365 // quadratic for this.
1366 // Neither of these are explicitly forbidden, but every compiler detects them
1367 // and warns.
1368
Sebastian Redl972041f2009-04-27 20:27:31 +00001369 CurFunctionNeedsScopeChecking = true;
Sebastian Redl8351da02008-12-22 21:35:02 +00001370 RawHandlers.release();
Ted Kremenek8189cde2009-02-07 01:47:29 +00001371 return Owned(new (Context) CXXTryStmt(TryLoc,
1372 static_cast<Stmt*>(TryBlock.release()),
1373 Handlers, NumHandlers));
Sebastian Redl8351da02008-12-22 21:35:02 +00001374}