blob: 5bd5c8a96b25bd113a3bc8c62e06f1169f807c61 [file] [log] [blame]
Chris Lattneraf8d5812006-11-10 05:07:45 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf8d5812006-11-10 05:07:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Richard Smith02e85f32011-04-14 22:09:26 +000018#include "clang/Sema/Lookup.h"
Chris Lattnerfc1c44a2007-08-23 05:46:52 +000019#include "clang/AST/ASTContext.h"
John McCall03318c12011-11-11 03:57:31 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner2ba5ca92009-08-16 16:57:27 +000024#include "clang/AST/ExprObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000025#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
John McCall2351cb92010-04-06 22:24:14 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregord0c22e02009-11-23 13:46:08 +000028#include "clang/Lex/Preprocessor.h"
Anders Carlsson290aa852007-11-25 00:25:21 +000029#include "clang/Basic/TargetInfo.h"
Chris Lattner70a4e9b2011-02-21 21:40:33 +000030#include "llvm/ADT/ArrayRef.h"
Chad Rosier592b90a2012-08-16 17:10:59 +000031#include "llvm/ADT/BitVector.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000032#include "llvm/ADT/STLExtras.h"
Richard Trieu451a5db2012-04-30 18:01:30 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor0a9f4e02012-05-16 16:11:17 +000034#include "llvm/ADT/SmallString.h"
Sebastian Redl63c4da02009-07-29 17:15:45 +000035#include "llvm/ADT/SmallVector.h"
Chad Rosier11ede932012-08-09 20:47:38 +000036#include "llvm/ADT/Triple.h"
37#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCContext.h"
Chad Rosier222ed4b2012-08-15 00:42:47 +000039#include "llvm/MC/MCInst.h"
40#include "llvm/MC/MCInstPrinter.h"
41#include "llvm/MC/MCInstrInfo.h"
Chad Rosier11ede932012-08-09 20:47:38 +000042#include "llvm/MC/MCObjectFileInfo.h"
43#include "llvm/MC/MCRegisterInfo.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSubtargetInfo.h"
46#include "llvm/MC/MCTargetAsmParser.h"
NAKAMURA Takumi19f29cf2012-08-15 04:19:08 +000047#include "llvm/MC/MCParser/MCAsmLexer.h"
Chad Rosier11ede932012-08-09 20:47:38 +000048#include "llvm/MC/MCParser/MCAsmParser.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TargetRegistry.h"
Chad Rosierd5c43a52012-08-09 17:33:11 +000051#include "llvm/Support/TargetSelect.h"
Chris Lattneraf8d5812006-11-10 05:07:45 +000052using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000053using namespace sema;
Chris Lattneraf8d5812006-11-10 05:07:45 +000054
John McCalldadc5752010-08-24 06:29:42 +000055StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
John McCallb268a282010-08-23 23:25:46 +000056 Expr *E = expr.get();
Douglas Gregora6e053e2010-12-15 01:34:56 +000057 if (!E) // FIXME: FullExprArg has no error state?
58 return StmtError();
59
Chris Lattner903eb512008-07-25 23:18:17 +000060 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
61 // void expression for its side effects. Conversion to void allows any
62 // operand, even incomplete types.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000063
Chris Lattner903eb512008-07-25 23:18:17 +000064 // Same thing in for stmt first clause (when expr) and third clause.
Sebastian Redl52f03ba2008-12-21 12:04:03 +000065 return Owned(static_cast<Stmt*>(E));
Chris Lattner1ec5f562007-06-27 05:38:08 +000066}
67
68
Argyrios Kyrtzidisf7620e42011-04-27 05:04:02 +000069StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
Argyrios Kyrtzidis43ea78b2011-09-01 21:53:45 +000070 bool HasLeadingEmptyMacro) {
71 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
Chris Lattner0f203a72007-05-28 01:45:28 +000072}
73
Chris Lattnerebb5c6c2011-02-18 01:27:55 +000074StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
75 SourceLocation EndLoc) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000076 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
Mike Stump11289f42009-09-09 15:08:12 +000077
Chris Lattnercbafe8d2009-04-12 20:13:14 +000078 // If we have an invalid decl, just return an error.
79 if (DG.isNull()) return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner34a22092009-03-04 04:23:07 +000081 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
Steve Naroff2a8ad182007-05-29 22:59:26 +000082}
Chris Lattneraf8d5812006-11-10 05:07:45 +000083
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000084void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
85 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000086
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000087 // If we have an invalid decl, just return.
88 if (DG.isNull() || !DG.isSingleDecl()) return;
John McCall31168b02011-06-15 23:02:42 +000089 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
90
Fariborz Jahaniane774fa62009-11-19 22:12:37 +000091 // suppress any potential 'unused variable' warning.
John McCall31168b02011-06-15 23:02:42 +000092 var->setUsed();
93
John McCalld4631322011-06-17 06:42:21 +000094 // foreach variables are never actually initialized in the way that
95 // the parser came up with.
96 var->setInit(0);
John McCall31168b02011-06-15 23:02:42 +000097
John McCalld4631322011-06-17 06:42:21 +000098 // In ARC, we don't need to retain the iteration variable of a fast
99 // enumeration loop. Rather than actually trying to catch that
100 // during declaration processing, we remove the consequences here.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000101 if (getLangOpts().ObjCAutoRefCount) {
John McCalld4631322011-06-17 06:42:21 +0000102 QualType type = var->getType();
103
104 // Only do this if we inferred the lifetime. Inferred lifetime
105 // will show up as a local qualifier because explicit lifetime
106 // should have shown up as an AttributedType instead.
107 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
108 // Add 'const' and mark the variable as pseudo-strong.
109 var->setType(type.withConst());
110 var->setARCPseudoStrong(true);
John McCall31168b02011-06-15 23:02:42 +0000111 }
112 }
Fariborz Jahaniane774fa62009-11-19 22:12:37 +0000113}
114
Chandler Carruthe2669392011-08-17 09:34:37 +0000115/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000116///
117/// Adding a cast to void (or other expression wrappers) will prevent the
118/// warning from firing.
Chandler Carruthe2669392011-08-17 09:34:37 +0000119static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000120 SourceLocation Loc;
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000121 bool IsNotEqual, CanAssign;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000122
123 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
124 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
Chandler Carruthe2669392011-08-17 09:34:37 +0000125 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000126
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000127 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000128 IsNotEqual = Op->getOpcode() == BO_NE;
129 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000130 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
131 if (Op->getOperator() != OO_EqualEqual &&
132 Op->getOperator() != OO_ExclaimEqual)
Chandler Carruthe2669392011-08-17 09:34:37 +0000133 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000134
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000135 Loc = Op->getOperatorLoc();
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000136 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
137 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000138 } else {
139 // Not a typo-prone comparison.
Chandler Carruthe2669392011-08-17 09:34:37 +0000140 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000141 }
142
143 // Suppress warnings when the operator, suspicious as it may be, comes from
144 // a macro expansion.
145 if (Loc.isMacroID())
Chandler Carruthe2669392011-08-17 09:34:37 +0000146 return false;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000147
Chandler Carruthe2669392011-08-17 09:34:37 +0000148 S.Diag(Loc, diag::warn_unused_comparison)
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000149 << (unsigned)IsNotEqual << E->getSourceRange();
150
Chandler Carruthe89ca5f2011-08-17 08:38:11 +0000151 // If the LHS is a plausible entity to assign to, provide a fixit hint to
152 // correct common typos.
153 if (CanAssign) {
154 if (IsNotEqual)
155 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
156 << FixItHint::CreateReplacement(Loc, "|=");
157 else
158 S.Diag(Loc, diag::note_equality_comparison_to_assign)
159 << FixItHint::CreateReplacement(Loc, "=");
160 }
Chandler Carruthe2669392011-08-17 09:34:37 +0000161
162 return true;
Chandler Carruthae51ecc2011-08-17 08:38:04 +0000163}
164
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000165void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +0000166 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
167 return DiagnoseUnusedExprResult(Label->getSubStmt());
168
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000169 const Expr *E = dyn_cast_or_null<Expr>(S);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000170 if (!E)
171 return;
172
Eli Friedmanc11535c2012-05-24 00:47:05 +0000173 const Expr *WarnExpr;
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000174 SourceLocation Loc;
175 SourceRange R1, R2;
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +0000176 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
Eli Friedmanc11535c2012-05-24 00:47:05 +0000177 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000178 return;
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner2ba5ca92009-08-16 16:57:27 +0000180 // Okay, we have an unused result. Depending on what the base expression is,
181 // we might want to make a more specific diagnostic. Check for one of these
182 // cases now.
183 unsigned DiagID = diag::warn_unused_expr;
John McCall5d413782010-12-06 08:20:24 +0000184 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
Douglas Gregor50dc2192010-02-11 22:55:30 +0000185 E = Temps->getSubExpr();
Chandler Carruthd05b3522011-02-21 00:56:56 +0000186 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
187 E = TempExpr->getSubExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000188
Chandler Carruthe2669392011-08-17 09:34:37 +0000189 if (DiagnoseUnusedComparison(*this, E))
190 return;
191
Eli Friedmanc11535c2012-05-24 00:47:05 +0000192 E = WarnExpr;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000193 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
John McCallc493a732010-03-12 07:11:26 +0000194 if (E->getType()->isVoidType())
195 return;
196
Chris Lattner1a6babf2009-10-13 04:53:48 +0000197 // If the callee has attribute pure, const, or warn_unused_result, warn with
198 // a more specific message to make it clear what is happening.
Nuno Lopes518e3702009-12-20 23:11:08 +0000199 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner1a6babf2009-10-13 04:53:48 +0000200 if (FD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000201 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Chris Lattner1a6babf2009-10-13 04:53:48 +0000202 return;
203 }
204 if (FD->getAttr<PureAttr>()) {
205 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
206 return;
207 }
208 if (FD->getAttr<ConstAttr>()) {
209 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
210 return;
211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212 }
John McCallb7bd14f2010-12-02 01:19:52 +0000213 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000214 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
John McCall31168b02011-06-15 23:02:42 +0000215 Diag(Loc, diag::err_arc_unused_init_message) << R1;
216 return;
217 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000218 const ObjCMethodDecl *MD = ME->getMethodDecl();
219 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Matt Beaumont-Gaya17cf632011-08-04 23:11:04 +0000220 Diag(Loc, diag::warn_unused_result) << R1 << R2;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000221 return;
222 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000223 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
224 const Expr *Source = POE->getSyntacticForm();
225 if (isa<ObjCSubscriptRefExpr>(Source))
226 DiagID = diag::warn_unused_container_subscript_expr;
227 else
228 DiagID = diag::warn_unused_property_expr;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000229 } else if (const CXXFunctionalCastExpr *FC
230 = dyn_cast<CXXFunctionalCastExpr>(E)) {
231 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
232 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
233 return;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +0000234 }
John McCall2351cb92010-04-06 22:24:14 +0000235 // Diagnose "(void*) blah" as a typo for "(void) blah".
236 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
237 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
238 QualType T = TI->getType();
239
240 // We really do want to use the non-canonical type here.
241 if (T == Context.VoidPtrTy) {
242 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
243
244 Diag(Loc, diag::warn_unused_voidptr)
245 << FixItHint::CreateRemoval(TL.getStarLoc());
246 return;
247 }
248 }
249
Eli Friedmanc11535c2012-05-24 00:47:05 +0000250 if (E->isGLValue() && E->getType().isVolatileQualified()) {
251 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
252 return;
253 }
254
Ted Kremenek3427fac2011-02-23 01:52:04 +0000255 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000256}
257
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000258void Sema::ActOnStartOfCompoundStmt() {
259 PushCompoundScope();
260}
261
262void Sema::ActOnFinishOfCompoundStmt() {
263 PopCompoundScope();
264}
265
266sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
267 return getCurFunction()->CompoundScopes.back();
268}
269
John McCalldadc5752010-08-24 06:29:42 +0000270StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000271Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000272 MultiStmtArg elts, bool isStmtExpr) {
273 unsigned NumElts = elts.size();
274 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
Chris Lattnerd864daf2007-08-27 04:29:41 +0000275 // If we're in C89 mode, check that we don't have any decls after stmts. If
276 // so, emit an extension diagnostic.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000277 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
Chris Lattnerd864daf2007-08-27 04:29:41 +0000278 // Note that __extension__ can be around a decl.
279 unsigned i = 0;
280 // Skip over all declarations.
281 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
282 /*empty*/;
283
284 // We found the end of the list or a statement. Scan for another declstmt.
285 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
286 /*empty*/;
Mike Stump11289f42009-09-09 15:08:12 +0000287
Chris Lattnerd864daf2007-08-27 04:29:41 +0000288 if (i != NumElts) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000289 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Chris Lattnerd864daf2007-08-27 04:29:41 +0000290 Diag(D->getLocation(), diag::ext_mixed_decls_code);
291 }
292 }
Chris Lattnercac27a52007-08-31 21:49:55 +0000293 // Warn about unused expressions in statements.
294 for (unsigned i = 0; i != NumElts; ++i) {
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000295 // Ignore statements that are last in a statement expression.
296 if (isStmtExpr && i == NumElts - 1)
Chris Lattnercac27a52007-08-31 21:49:55 +0000297 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000298
Anders Carlsson59a2ab92009-07-30 22:17:18 +0000299 DiagnoseUnusedExprResult(Elts[i]);
Chris Lattnercac27a52007-08-31 21:49:55 +0000300 }
Sebastian Redl52f03ba2008-12-21 12:04:03 +0000301
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000302 // Check for suspicious empty body (null statement) in `for' and `while'
303 // statements. Don't do anything for template instantiations, this just adds
304 // noise.
305 if (NumElts != 0 && !CurrentInstantiationScope &&
306 getCurCompoundScope().HasEmptyLoopBodies) {
307 for (unsigned i = 0; i != NumElts - 1; ++i)
308 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
309 }
310
Ted Kremenek5a201952009-02-07 01:47:29 +0000311 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000312}
313
John McCalldadc5752010-08-24 06:29:42 +0000314StmtResult
John McCallb268a282010-08-23 23:25:46 +0000315Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
316 SourceLocation DotDotDotLoc, Expr *RHSVal,
Chris Lattner34a22092009-03-04 04:23:07 +0000317 SourceLocation ColonLoc) {
John McCallb268a282010-08-23 23:25:46 +0000318 assert((LHSVal != 0) && "missing expression in case statement");
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000319
John McCallaab3e412010-08-25 08:40:02 +0000320 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000321 Diag(CaseLoc, diag::err_case_not_in_switch);
Chris Lattner34a22092009-03-04 04:23:07 +0000322 return StmtError();
Chris Lattner54f4d2b2007-07-23 17:05:23 +0000323 }
Chris Lattner35e287b2007-06-03 01:44:43 +0000324
David Blaikiebbafb8a2012-03-11 07:00:24 +0000325 if (!getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000326 // C99 6.8.4.2p3: The expression shall be an integer constant.
327 // However, GCC allows any evaluatable integer expression.
Richard Smithf4c51d92012-02-04 09:53:13 +0000328 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
329 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
330 if (!LHSVal)
331 return StmtError();
332 }
Richard Smithf8379a02012-01-18 23:55:52 +0000333
334 // GCC extension: The expression shall be an integer constant.
335
Richard Smithf4c51d92012-02-04 09:53:13 +0000336 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
337 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
338 // Recover from an error by just forgetting about it.
Richard Smithf8379a02012-01-18 23:55:52 +0000339 }
340 }
341
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000342 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
343 ColonLoc);
John McCallaab3e412010-08-25 08:40:02 +0000344 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000345 return Owned(CS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000346}
347
Chris Lattner34a22092009-03-04 04:23:07 +0000348/// ActOnCaseStmtBody - This installs a statement as the body of a case.
John McCallb268a282010-08-23 23:25:46 +0000349void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000350 DiagnoseUnusedExprResult(SubStmt);
351
Chris Lattner34a22092009-03-04 04:23:07 +0000352 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
Chris Lattner34a22092009-03-04 04:23:07 +0000353 CS->setSubStmt(SubStmt);
354}
355
John McCalldadc5752010-08-24 06:29:42 +0000356StmtResult
Mike Stump11289f42009-09-09 15:08:12 +0000357Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +0000358 Stmt *SubStmt, Scope *CurScope) {
Chandler Carruth2b949c22011-08-18 02:04:29 +0000359 DiagnoseUnusedExprResult(SubStmt);
360
John McCallaab3e412010-08-25 08:40:02 +0000361 if (getCurFunction()->SwitchStack.empty()) {
Chris Lattner39407372007-07-21 03:00:26 +0000362 Diag(DefaultLoc, diag::err_default_not_in_switch);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000363 return Owned(SubStmt);
Chris Lattner39407372007-07-21 03:00:26 +0000364 }
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000365
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000366 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
John McCallaab3e412010-08-25 08:40:02 +0000367 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
Sebastian Redl1cbb59182008-12-28 16:13:43 +0000368 return Owned(DS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000369}
370
John McCalldadc5752010-08-24 06:29:42 +0000371StmtResult
Chris Lattnercab02a62011-02-17 20:34:02 +0000372Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
373 SourceLocation ColonLoc, Stmt *SubStmt) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000374 // If the label was multiply defined, reject it now.
375 if (TheDecl->getStmt()) {
376 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
377 Diag(TheDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000378 return Owned(SubStmt);
Chris Lattnere2473062007-05-28 06:28:18 +0000379 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000380
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000381 // Otherwise, things are good. Fill in the declaration and return it.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000382 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
383 TheDecl->setStmt(LS);
Abramo Bagnara124fdf62011-03-03 18:24:14 +0000384 if (!TheDecl->isGnuLocal())
385 TheDecl->setLocation(IdentLoc);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000386 return Owned(LS);
Chris Lattneraf8d5812006-11-10 05:07:45 +0000387}
388
Richard Smithc202b282012-04-14 00:33:13 +0000389StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000390 ArrayRef<const Attr*> Attrs,
Richard Smithc202b282012-04-14 00:33:13 +0000391 Stmt *SubStmt) {
Alexander Kornienko20f6fc62012-07-09 10:04:07 +0000392 // Fill in the declaration and return it.
393 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
Richard Smithc202b282012-04-14 00:33:13 +0000394 return Owned(LS);
395}
396
John McCalldadc5752010-08-24 06:29:42 +0000397StmtResult
John McCall48871652010-08-21 09:40:31 +0000398Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000399 Stmt *thenStmt, SourceLocation ElseLoc,
400 Stmt *elseStmt) {
John McCalldadc5752010-08-24 06:29:42 +0000401 ExprResult CondResult(CondVal.release());
Mike Stump11289f42009-09-09 15:08:12 +0000402
Douglas Gregor633caca2009-11-23 23:44:04 +0000403 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000404 if (CondVar) {
405 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000406 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000407 if (CondResult.isInvalid())
408 return StmtError();
Douglas Gregor633caca2009-11-23 23:44:04 +0000409 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +0000410 Expr *ConditionExpr = CondResult.takeAs<Expr>();
411 if (!ConditionExpr)
412 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000414 DiagnoseUnusedExprResult(thenStmt);
Steve Naroff86272ea2007-05-29 02:14:17 +0000415
John McCallb268a282010-08-23 23:25:46 +0000416 if (!elseStmt) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +0000417 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
418 diag::warn_empty_if_body);
Anders Carlssondb83d772007-10-10 20:50:11 +0000419 }
420
Anders Carlsson5c5f1602009-07-30 22:39:03 +0000421 DiagnoseUnusedExprResult(elseStmt);
Mike Stump11289f42009-09-09 15:08:12 +0000422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
Argyrios Kyrtzidisde2bdf62010-11-20 02:04:01 +0000424 thenStmt, ElseLoc, elseStmt));
Chris Lattneraf8d5812006-11-10 05:07:45 +0000425}
Steve Naroff86272ea2007-05-29 02:14:17 +0000426
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000427/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
428/// the specified width and sign. If an overflow occurs, detect it and emit
429/// the specified diagnostic.
430void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
431 unsigned NewWidth, bool NewSign,
Mike Stump11289f42009-09-09 15:08:12 +0000432 SourceLocation Loc,
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000433 unsigned DiagID) {
434 // Perform a conversion to the promoted condition type if needed.
435 if (NewWidth > Val.getBitWidth()) {
436 // If this is an extension, just do it.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000437 Val = Val.extend(NewWidth);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000438 Val.setIsSigned(NewSign);
Douglas Gregora070ffa2010-03-01 01:04:55 +0000439
440 // If the input was signed and negative and the output is
441 // unsigned, don't bother to warn: this is implementation-defined
442 // behavior.
443 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000444 } else if (NewWidth < Val.getBitWidth()) {
445 // If this is a truncation, check for overflow.
446 llvm::APSInt ConvVal(Val);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000447 ConvVal = ConvVal.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000448 ConvVal.setIsSigned(NewSign);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000449 ConvVal = ConvVal.extend(Val.getBitWidth());
Chris Lattner247ef952007-08-23 22:08:35 +0000450 ConvVal.setIsSigned(Val.isSigned());
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000451 if (ConvVal != Val)
Chris Lattner29e812b2008-11-20 06:06:08 +0000452 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000453
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000454 // Regardless of whether a diagnostic was emitted, really do the
455 // truncation.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000456 Val = Val.trunc(NewWidth);
Chris Lattner247ef952007-08-23 22:08:35 +0000457 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000458 } else if (NewSign != Val.isSigned()) {
459 // Convert the sign to match the sign of the condition. This can cause
460 // overflow as well: unsigned(INTMIN)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000461 // We don't diagnose this overflow, because it is implementation-defined
Douglas Gregore5ad57a2010-02-18 00:56:01 +0000462 // behavior.
463 // FIXME: Introduce a second, default-ignored warning for this case?
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000464 llvm::APSInt OldVal(Val);
465 Val.setIsSigned(NewSign);
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000466 }
467}
468
Chris Lattner67998452007-08-23 18:29:20 +0000469namespace {
470 struct CaseCompareFunctor {
471 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
472 const llvm::APSInt &RHS) {
473 return LHS.first < RHS;
474 }
Chris Lattner1463cca2007-09-03 18:31:57 +0000475 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
476 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
477 return LHS.first < RHS.first;
478 }
Chris Lattner67998452007-08-23 18:29:20 +0000479 bool operator()(const llvm::APSInt &LHS,
480 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
481 return LHS < RHS.first;
482 }
483 };
484}
485
Chris Lattner4b2ff022007-09-21 18:15:22 +0000486/// CmpCaseVals - Comparison predicate for sorting case values.
487///
488static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
489 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
490 if (lhs.first < rhs.first)
491 return true;
492
493 if (lhs.first == rhs.first &&
494 lhs.second->getCaseLoc().getRawEncoding()
495 < rhs.second->getCaseLoc().getRawEncoding())
496 return true;
497 return false;
498}
499
Douglas Gregorbd6839732010-02-08 22:24:16 +0000500/// CmpEnumVals - Comparison predicate for sorting enumeration values.
501///
502static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
503 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
504{
505 return lhs.first < rhs.first;
506}
507
508/// EqEnumVals - Comparison preficate for uniqing enumeration values.
509///
510static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
511 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
512{
513 return lhs.first == rhs.first;
514}
515
Chris Lattnera96d4272009-10-16 16:45:22 +0000516/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
517/// potentially integral-promoted expression @p expr.
John McCall5939b162011-08-06 07:30:58 +0000518static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
519 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
520 expr = cleanups->getSubExpr();
521 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
522 if (impcast->getCastKind() != CK_IntegralCast) break;
523 expr = impcast->getSubExpr();
Chris Lattnera96d4272009-10-16 16:45:22 +0000524 }
525 return expr->getType();
526}
527
John McCalldadc5752010-08-24 06:29:42 +0000528StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
John McCall48871652010-08-21 09:40:31 +0000530 Decl *CondVar) {
John McCalldadc5752010-08-24 06:29:42 +0000531 ExprResult CondResult;
John McCallb268a282010-08-23 23:25:46 +0000532
Douglas Gregore60e41a2010-05-06 17:25:47 +0000533 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +0000534 if (CondVar) {
535 ConditionVar = cast<VarDecl>(CondVar);
John McCallb268a282010-08-23 23:25:46 +0000536 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
537 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000538 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
John McCallb268a282010-08-23 23:25:46 +0000540 Cond = CondResult.release();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000542
John McCallb268a282010-08-23 23:25:46 +0000543 if (!Cond)
Douglas Gregore60e41a2010-05-06 17:25:47 +0000544 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000545
Douglas Gregore2b37442012-05-04 22:38:52 +0000546 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
547 Expr *Cond;
Chad Rosiercc6a9082012-06-20 18:51:04 +0000548
Douglas Gregore2b37442012-05-04 22:38:52 +0000549 public:
550 SwitchConvertDiagnoser(Expr *Cond)
551 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000552
Douglas Gregore2b37442012-05-04 22:38:52 +0000553 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
554 QualType T) {
555 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
556 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000557
Douglas Gregore2b37442012-05-04 22:38:52 +0000558 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
559 QualType T) {
560 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
561 << T << Cond->getSourceRange();
562 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000563
Douglas Gregore2b37442012-05-04 22:38:52 +0000564 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
565 QualType T,
566 QualType ConvTy) {
567 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
568 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000569
Douglas Gregore2b37442012-05-04 22:38:52 +0000570 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
571 QualType ConvTy) {
572 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
573 << ConvTy->isEnumeralType() << ConvTy;
574 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000575
Douglas Gregore2b37442012-05-04 22:38:52 +0000576 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
577 QualType T) {
578 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
579 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000580
Douglas Gregore2b37442012-05-04 22:38:52 +0000581 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
582 QualType ConvTy) {
583 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
584 << ConvTy->isEnumeralType() << ConvTy;
585 }
Chad Rosiercc6a9082012-06-20 18:51:04 +0000586
Douglas Gregore2b37442012-05-04 22:38:52 +0000587 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
588 QualType T,
589 QualType ConvTy) {
590 return DiagnosticBuilder::getEmpty();
591 }
592 } SwitchDiagnoser(Cond);
593
John McCallb268a282010-08-23 23:25:46 +0000594 CondResult
Douglas Gregore2b37442012-05-04 22:38:52 +0000595 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
Richard Smith8dd34252012-02-04 07:07:42 +0000596 /*AllowScopedEnumerations*/ true);
John McCallb268a282010-08-23 23:25:46 +0000597 if (CondResult.isInvalid()) return StmtError();
598 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599
John McCall5939b162011-08-06 07:30:58 +0000600 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
601 CondResult = UsualUnaryConversions(Cond);
602 if (CondResult.isInvalid()) return StmtError();
603 Cond = CondResult.take();
604
John McCall48871652010-08-21 09:40:31 +0000605 if (!CondVar) {
John McCallacf0ee52010-10-08 02:01:28 +0000606 CheckImplicitConversions(Cond, SwitchLoc);
John McCall5d413782010-12-06 08:20:24 +0000607 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +0000608 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +0000609 return StmtError();
John McCallb268a282010-08-23 23:25:46 +0000610 Cond = CondResult.take();
Douglas Gregore60e41a2010-05-06 17:25:47 +0000611 }
John McCalla95172b2010-08-01 00:26:45 +0000612
John McCallaab3e412010-08-25 08:40:02 +0000613 getCurFunction()->setHasBranchIntoScope();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
John McCallb268a282010-08-23 23:25:46 +0000615 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
John McCallaab3e412010-08-25 08:40:02 +0000616 getCurFunction()->SwitchStack.push_back(SS);
Douglas Gregore60e41a2010-05-06 17:25:47 +0000617 return Owned(SS);
Chris Lattner8fd2d012010-01-24 01:50:29 +0000618}
619
Gabor Greif16e02862010-10-01 22:05:14 +0000620static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
621 if (Val.getBitWidth() < BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000622 Val = Val.extend(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000623 else if (Val.getBitWidth() > BitWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +0000624 Val = Val.trunc(BitWidth);
Gabor Greif16e02862010-10-01 22:05:14 +0000625 Val.setIsSigned(IsSigned);
626}
627
John McCalldadc5752010-08-24 06:29:42 +0000628StmtResult
John McCallb268a282010-08-23 23:25:46 +0000629Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
630 Stmt *BodyStmt) {
631 SwitchStmt *SS = cast<SwitchStmt>(Switch);
John McCallaab3e412010-08-25 08:40:02 +0000632 assert(SS == getCurFunction()->SwitchStack.back() &&
633 "switch stack missing push/pop!");
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000634
Steve Naroff42a350a2007-09-01 21:08:38 +0000635 SS->setBody(BodyStmt, SwitchLoc);
John McCallaab3e412010-08-25 08:40:02 +0000636 getCurFunction()->SwitchStack.pop_back();
Anders Carlsson51873c22007-07-22 07:07:56 +0000637
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000638 Expr *CondExpr = SS->getCond();
John McCall5939b162011-08-06 07:30:58 +0000639 if (!CondExpr) return StmtError();
640
641 QualType CondType = CondExpr->getType();
642
John McCalld3dfbd62010-05-18 03:19:21 +0000643 Expr *CondExprBeforePromotion = CondExpr;
Douglas Gregord0c22e02009-11-23 13:46:08 +0000644 QualType CondTypeBeforePromotion =
John McCall5939b162011-08-06 07:30:58 +0000645 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
Douglas Gregord0c22e02009-11-23 13:46:08 +0000646
Chris Lattnera96d4272009-10-16 16:45:22 +0000647 // C++ 6.4.2.p2:
648 // Integral promotions are performed (on the switch condition).
649 //
650 // A case value unrepresentable by the original switch condition
651 // type (before the promotion) doesn't make sense, even when it can
652 // be represented by the promoted type. Therefore we need to find
653 // the pre-promotion type of the switch condition.
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000654 if (!CondExpr->isTypeDependent()) {
Douglas Gregor5823da32010-06-29 23:25:20 +0000655 // We have already converted the expression to an integral or enumeration
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656 // type, when we started the switch statement. If we don't have an
Douglas Gregor5823da32010-06-29 23:25:20 +0000657 // appropriate type now, just return an error.
658 if (!CondType->isIntegralOrEnumerationType())
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000659 return StmtError();
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000660
Chris Lattner4ebae652010-04-16 23:34:13 +0000661 if (CondExpr->isKnownToHaveBooleanValue()) {
Edward O'Callaghan93135aa2009-10-17 19:32:54 +0000662 // switch(bool_expr) {...} is often a programmer error, e.g.
663 // switch(n && mask) { ... } // Doh - should be "n & mask".
664 // One can always use an if statement instead of switch(bool_expr).
665 Diag(SwitchLoc, diag::warn_bool_switch_condition)
666 << CondExpr->getSourceRange();
667 }
Anders Carlsson51873c22007-07-22 07:07:56 +0000668 }
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000669
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000670 // Get the bitwidth of the switched-on value before promotions. We must
671 // convert the integer case values to this width before comparison.
Mike Stump11289f42009-09-09 15:08:12 +0000672 bool HasDependentValue
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000673 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
Mike Stump11289f42009-09-09 15:08:12 +0000674 unsigned CondWidth
Chris Lattnerabcf38a2011-02-24 07:31:28 +0000675 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
Chad Rosier02a84392012-08-10 17:56:09 +0000676 bool CondIsSigned
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000677 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000679 // Accumulate all of the case values in a vector so that we can sort them
680 // and detect duplicates. This vector contains the APInt for the case after
681 // it has been converted to the condition type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000682 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
Chris Lattner67998452007-08-23 18:29:20 +0000683 CaseValsTy CaseVals;
Mike Stump11289f42009-09-09 15:08:12 +0000684
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000685 // Keep track of any GNU case ranges we see. The APSInt is the low value.
Douglas Gregorbd6839732010-02-08 22:24:16 +0000686 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
687 CaseRangesTy CaseRanges;
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000689 DefaultStmt *TheDefaultStmt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000690
Chris Lattner10cb5e52007-08-23 06:23:56 +0000691 bool CaseListIsErroneous = false;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000693 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
Anders Carlsson51873c22007-07-22 07:07:56 +0000694 SC = SC->getNextSwitchCase()) {
Mike Stump11289f42009-09-09 15:08:12 +0000695
Anders Carlsson51873c22007-07-22 07:07:56 +0000696 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000697 if (TheDefaultStmt) {
698 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
Chris Lattner0369c572008-11-23 23:12:31 +0000699 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
Sebastian Redl6a8002e2009-01-11 00:38:46 +0000700
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000701 // FIXME: Remove the default statement from the switch block so that
Mike Stump87c57ac2009-05-16 07:39:55 +0000702 // we'll return a valid AST. This requires recursing down the AST and
703 // finding it, not something we are set up to do right now. For now,
704 // just lop the entire switch stmt out of the AST.
Chris Lattner10cb5e52007-08-23 06:23:56 +0000705 CaseListIsErroneous = true;
Anders Carlsson51873c22007-07-22 07:07:56 +0000706 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000707 TheDefaultStmt = DS;
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000709 } else {
710 CaseStmt *CS = cast<CaseStmt>(SC);
Mike Stump11289f42009-09-09 15:08:12 +0000711
Chris Lattnera65e1f32008-01-16 19:17:22 +0000712 Expr *Lo = CS->getLHS();
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000713
714 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
715 HasDependentValue = true;
716 break;
717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Richard Smithf8379a02012-01-18 23:55:52 +0000719 llvm::APSInt LoVal;
Mike Stump11289f42009-09-09 15:08:12 +0000720
David Blaikiebbafb8a2012-03-11 07:00:24 +0000721 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000722 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
723 // constant expression of the promoted type of the switch condition.
724 ExprResult ConvLo =
725 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
726 if (ConvLo.isInvalid()) {
727 CaseListIsErroneous = true;
728 continue;
729 }
730 Lo = ConvLo.take();
731 } else {
732 // We already verified that the expression has a i-c-e value (C99
733 // 6.8.4.2p3) - get that value now.
734 LoVal = Lo->EvaluateKnownConstInt(Context);
735
736 // If the LHS is not the same type as the condition, insert an implicit
737 // cast.
738 Lo = DefaultLvalueConversion(Lo).take();
739 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
740 }
741
742 // Convert the value to the same width/sign as the condition had prior to
743 // integral promotions.
744 //
745 // FIXME: This causes us to reject valid code:
746 // switch ((char)c) { case 256: case 0: return 0; }
747 // Here we claim there is a duplicated condition value, but there is not.
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000748 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000749 Lo->getLocStart(),
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000750 diag::warn_case_value_overflow);
Anders Carlsson51873c22007-07-22 07:07:56 +0000751
Chris Lattnera65e1f32008-01-16 19:17:22 +0000752 CS->setLHS(Lo);
Mike Stump11289f42009-09-09 15:08:12 +0000753
Chris Lattner10cb5e52007-08-23 06:23:56 +0000754 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000755 if (CS->getRHS()) {
Mike Stump11289f42009-09-09 15:08:12 +0000756 if (CS->getRHS()->isTypeDependent() ||
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000757 CS->getRHS()->isValueDependent()) {
758 HasDependentValue = true;
759 break;
760 }
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000761 CaseRanges.push_back(std::make_pair(LoVal, CS));
Mike Stump11289f42009-09-09 15:08:12 +0000762 } else
Chris Lattner10cb5e52007-08-23 06:23:56 +0000763 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattnerfc1c44a2007-08-23 05:46:52 +0000764 }
765 }
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000766
767 if (!HasDependentValue) {
John McCalld3dfbd62010-05-18 03:19:21 +0000768 // If we don't have a default statement, check whether the
769 // condition is constant.
770 llvm::APSInt ConstantCondValue;
771 bool HasConstantCond = false;
John McCalld3dfbd62010-05-18 03:19:21 +0000772 if (!HasDependentValue && !TheDefaultStmt) {
Richard Smith7b553f12011-10-29 00:50:52 +0000773 HasConstantCond
Richard Smith5fab0c92011-12-28 19:48:30 +0000774 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
775 Expr::SE_AllowSideEffects);
776 assert(!HasConstantCond ||
777 (ConstantCondValue.getBitWidth() == CondWidth &&
778 ConstantCondValue.isSigned() == CondIsSigned));
John McCalld3dfbd62010-05-18 03:19:21 +0000779 }
Richard Smith5fab0c92011-12-28 19:48:30 +0000780 bool ShouldCheckConstantCond = HasConstantCond;
John McCalld3dfbd62010-05-18 03:19:21 +0000781
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000782 // Sort all the scalar case values so we can easily detect duplicates.
783 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
784
785 if (!CaseVals.empty()) {
John McCalld3dfbd62010-05-18 03:19:21 +0000786 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
787 if (ShouldCheckConstantCond &&
788 CaseVals[i].first == ConstantCondValue)
789 ShouldCheckConstantCond = false;
790
791 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000792 // If we have a duplicate, report it.
Douglas Gregor9841df62012-05-16 05:32:58 +0000793 // First, determine if either case value has a name
794 StringRef PrevString, CurrString;
795 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
796 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
797 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
798 PrevString = DeclRef->getDecl()->getName();
799 }
800 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
801 CurrString = DeclRef->getDecl()->getName();
802 }
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000803 llvm::SmallString<16> CaseValStr;
804 CaseVals[i-1].first.toString(CaseValStr);
Douglas Gregor9841df62012-05-16 05:32:58 +0000805
806 if (PrevString == CurrString)
807 Diag(CaseVals[i].second->getLHS()->getLocStart(),
808 diag::err_duplicate_case) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000809 (PrevString.empty() ? CaseValStr.str() : PrevString);
Douglas Gregor9841df62012-05-16 05:32:58 +0000810 else
811 Diag(CaseVals[i].second->getLHS()->getLocStart(),
812 diag::err_duplicate_case_differing_expr) <<
Douglas Gregor0a9f4e02012-05-16 16:11:17 +0000813 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
814 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
Douglas Gregor9841df62012-05-16 05:32:58 +0000815 CaseValStr;
816
John McCalld3dfbd62010-05-18 03:19:21 +0000817 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000818 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000819 // FIXME: We really want to remove the bogus case stmt from the
820 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000821 CaseListIsErroneous = true;
822 }
823 }
824 }
Mike Stump11289f42009-09-09 15:08:12 +0000825
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000826 // Detect duplicate case ranges, which usually don't exist at all in
827 // the first place.
828 if (!CaseRanges.empty()) {
829 // Sort all the case ranges by their low value so we can easily detect
830 // overlaps between ranges.
831 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
Mike Stump11289f42009-09-09 15:08:12 +0000832
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000833 // Scan the ranges, computing the high values and removing empty ranges.
834 std::vector<llvm::APSInt> HiVals;
835 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
John McCalld3dfbd62010-05-18 03:19:21 +0000836 llvm::APSInt &LoVal = CaseRanges[i].first;
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000837 CaseStmt *CR = CaseRanges[i].second;
838 Expr *Hi = CR->getRHS();
Richard Smithf8379a02012-01-18 23:55:52 +0000839 llvm::APSInt HiVal;
840
David Blaikiebbafb8a2012-03-11 07:00:24 +0000841 if (getLangOpts().CPlusPlus0x) {
Richard Smithf8379a02012-01-18 23:55:52 +0000842 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
843 // constant expression of the promoted type of the switch condition.
844 ExprResult ConvHi =
845 CheckConvertedConstantExpression(Hi, CondType, HiVal,
846 CCEK_CaseValue);
847 if (ConvHi.isInvalid()) {
848 CaseListIsErroneous = true;
849 continue;
850 }
851 Hi = ConvHi.take();
852 } else {
853 HiVal = Hi->EvaluateKnownConstInt(Context);
854
855 // If the RHS is not the same type as the condition, insert an
856 // implicit cast.
857 Hi = DefaultLvalueConversion(Hi).take();
858 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000861 // Convert the value to the same width/sign as the condition.
862 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
Gabor Greif16e02862010-10-01 22:05:14 +0000863 Hi->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000864 diag::warn_case_value_overflow);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000866 CR->setRHS(Hi);
Mike Stump11289f42009-09-09 15:08:12 +0000867
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000868 // If the low value is bigger than the high value, the case is empty.
John McCalld3dfbd62010-05-18 03:19:21 +0000869 if (LoVal > HiVal) {
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000870 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
871 << SourceRange(CR->getLHS()->getLocStart(),
Gabor Greif16e02862010-10-01 22:05:14 +0000872 Hi->getLocEnd());
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000873 CaseRanges.erase(CaseRanges.begin()+i);
874 --i, --e;
875 continue;
876 }
John McCalld3dfbd62010-05-18 03:19:21 +0000877
878 if (ShouldCheckConstantCond &&
879 LoVal <= ConstantCondValue &&
880 ConstantCondValue <= HiVal)
881 ShouldCheckConstantCond = false;
882
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000883 HiVals.push_back(HiVal);
884 }
Mike Stump11289f42009-09-09 15:08:12 +0000885
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000886 // Rescan the ranges, looking for overlap with singleton values and other
887 // ranges. Since the range list is sorted, we only need to compare case
888 // ranges with their neighbors.
889 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
890 llvm::APSInt &CRLo = CaseRanges[i].first;
891 llvm::APSInt &CRHi = HiVals[i];
892 CaseStmt *CR = CaseRanges[i].second;
Mike Stump11289f42009-09-09 15:08:12 +0000893
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000894 // Check to see whether the case range overlaps with any
895 // singleton cases.
896 CaseStmt *OverlapStmt = 0;
897 llvm::APSInt OverlapVal(32);
Mike Stump11289f42009-09-09 15:08:12 +0000898
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000899 // Find the smallest value >= the lower bound. If I is in the
900 // case range, then we have overlap.
901 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
902 CaseVals.end(), CRLo,
903 CaseCompareFunctor());
904 if (I != CaseVals.end() && I->first < CRHi) {
905 OverlapVal = I->first; // Found overlap with scalar.
906 OverlapStmt = I->second;
907 }
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000909 // Find the smallest value bigger than the upper bound.
910 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
911 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
912 OverlapVal = (I-1)->first; // Found overlap with scalar.
913 OverlapStmt = (I-1)->second;
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000916 // Check to see if this case stmt overlaps with the subsequent
917 // case range.
918 if (i && CRLo <= HiVals[i-1]) {
919 OverlapVal = HiVals[i-1]; // Found overlap with range.
920 OverlapStmt = CaseRanges[i-1].second;
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000923 if (OverlapStmt) {
924 // If we have a duplicate, report it.
925 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
926 << OverlapVal.toString(10);
Mike Stump11289f42009-09-09 15:08:12 +0000927 Diag(OverlapStmt->getLHS()->getLocStart(),
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000928 diag::note_duplicate_case_prev);
Mike Stump87c57ac2009-05-16 07:39:55 +0000929 // FIXME: We really want to remove the bogus case stmt from the
930 // substmt, but we have no way to do this right now.
Douglas Gregor2a2d00f2009-05-15 23:57:33 +0000931 CaseListIsErroneous = true;
932 }
Chris Lattnerfcb920d2007-08-23 14:29:07 +0000933 }
Chris Lattner10cb5e52007-08-23 06:23:56 +0000934 }
Douglas Gregorbd6839732010-02-08 22:24:16 +0000935
John McCalld3dfbd62010-05-18 03:19:21 +0000936 // Complain if we have a constant condition and we didn't find a match.
937 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
938 // TODO: it would be nice if we printed enums as enums, chars as
939 // chars, etc.
940 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
941 << ConstantCondValue.toString(10)
942 << CondExpr->getSourceRange();
943 }
944
945 // Check to see if switch is over an Enum and handles all of its
Ted Kremenekc42f3452010-09-09 00:05:53 +0000946 // values. We only issue a warning if there is not 'default:', but
947 // we still do the analysis to preserve this information in the AST
948 // (which can be used by flow-based analyes).
John McCalld3dfbd62010-05-18 03:19:21 +0000949 //
Chris Lattner51679082010-09-16 17:09:42 +0000950 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
Ted Kremenekc42f3452010-09-09 00:05:53 +0000951
Douglas Gregorbd6839732010-02-08 22:24:16 +0000952 // If switch has default case, then ignore it.
Ted Kremenekc42f3452010-09-09 00:05:53 +0000953 if (!CaseListIsErroneous && !HasConstantCond && ET) {
Douglas Gregorbd6839732010-02-08 22:24:16 +0000954 const EnumDecl *ED = ET->getDecl();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000955 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
Francois Pichetfbf7e172011-06-02 00:47:27 +0000956 EnumValsTy;
Douglas Gregorbd6839732010-02-08 22:24:16 +0000957 EnumValsTy EnumVals;
958
John McCalld3dfbd62010-05-18 03:19:21 +0000959 // Gather all enum values, set their type and sort them,
960 // allowing easier comparison with CaseVals.
961 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
Gabor Greif16e02862010-10-01 22:05:14 +0000962 EDI != ED->enumerator_end(); ++EDI) {
963 llvm::APSInt Val = EDI->getInitVal();
964 AdjustAPSInt(Val, CondWidth, CondIsSigned);
David Blaikie40ed2972012-06-06 20:45:41 +0000965 EnumVals.push_back(std::make_pair(Val, *EDI));
Douglas Gregorbd6839732010-02-08 22:24:16 +0000966 }
967 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
John McCalld3dfbd62010-05-18 03:19:21 +0000968 EnumValsTy::iterator EIend =
969 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Ted Kremenekc42f3452010-09-09 00:05:53 +0000970
971 // See which case values aren't in enum.
David Blaikiee476f972012-01-22 02:31:55 +0000972 EnumValsTy::const_iterator EI = EnumVals.begin();
973 for (CaseValsTy::const_iterator CI = CaseVals.begin();
974 CI != CaseVals.end(); CI++) {
975 while (EI != EIend && EI->first < CI->first)
976 EI++;
977 if (EI == EIend || EI->first > CI->first)
978 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000979 << CondTypeBeforePromotion;
David Blaikiee476f972012-01-22 02:31:55 +0000980 }
981 // See which of case ranges aren't in enum
982 EI = EnumVals.begin();
983 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
984 RI != CaseRanges.end() && EI != EIend; RI++) {
985 while (EI != EIend && EI->first < RI->first)
986 EI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987
David Blaikiee476f972012-01-22 02:31:55 +0000988 if (EI == EIend || EI->first != RI->first) {
989 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +0000990 << CondTypeBeforePromotion;
Ted Kremenek02627a22010-09-09 06:53:59 +0000991 }
David Blaikiee476f972012-01-22 02:31:55 +0000992
Chad Rosier02a84392012-08-10 17:56:09 +0000993 llvm::APSInt Hi =
David Blaikiee476f972012-01-22 02:31:55 +0000994 RI->second->getRHS()->EvaluateKnownConstInt(Context);
995 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
996 while (EI != EIend && EI->first < Hi)
997 EI++;
998 if (EI == EIend || EI->first != Hi)
999 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
Fariborz Jahaniana6983a92012-03-21 20:56:29 +00001000 << CondTypeBeforePromotion;
Douglas Gregorbd6839732010-02-08 22:24:16 +00001001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002
Ted Kremenekc42f3452010-09-09 00:05:53 +00001003 // Check which enum vals aren't in switch
Douglas Gregorbd6839732010-02-08 22:24:16 +00001004 CaseValsTy::const_iterator CI = CaseVals.begin();
1005 CaseRangesTy::const_iterator RI = CaseRanges.begin();
Ted Kremenekc42f3452010-09-09 00:05:53 +00001006 bool hasCasesNotInSwitch = false;
1007
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001008 SmallVector<DeclarationName,8> UnhandledNames;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
David Blaikiee476f972012-01-22 02:31:55 +00001010 for (EI = EnumVals.begin(); EI != EIend; EI++){
Chris Lattner51679082010-09-16 17:09:42 +00001011 // Drop unneeded case values
Douglas Gregorbd6839732010-02-08 22:24:16 +00001012 llvm::APSInt CIVal;
1013 while (CI != CaseVals.end() && CI->first < EI->first)
1014 CI++;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015
Douglas Gregorbd6839732010-02-08 22:24:16 +00001016 if (CI != CaseVals.end() && CI->first == EI->first)
1017 continue;
1018
Ted Kremenekc42f3452010-09-09 00:05:53 +00001019 // Drop unneeded case ranges
Douglas Gregorbd6839732010-02-08 22:24:16 +00001020 for (; RI != CaseRanges.end(); RI++) {
Richard Smithcaf33902011-10-10 18:28:20 +00001021 llvm::APSInt Hi =
1022 RI->second->getRHS()->EvaluateKnownConstInt(Context);
Gabor Greif16e02862010-10-01 22:05:14 +00001023 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
Douglas Gregorbd6839732010-02-08 22:24:16 +00001024 if (EI->first <= Hi)
1025 break;
1026 }
1027
Ted Kremenekc42f3452010-09-09 00:05:53 +00001028 if (RI == CaseRanges.end() || EI->first < RI->first) {
Ted Kremenek02627a22010-09-09 06:53:59 +00001029 hasCasesNotInSwitch = true;
David Blaikie645ae0c2012-01-21 18:12:07 +00001030 UnhandledNames.push_back(EI->second->getDeclName());
Ted Kremenek02627a22010-09-09 06:53:59 +00001031 }
Douglas Gregorbd6839732010-02-08 22:24:16 +00001032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
David Blaikie60ac6382012-01-23 04:46:12 +00001034 if (TheDefaultStmt && UnhandledNames.empty())
1035 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
David Blaikie645ae0c2012-01-21 18:12:07 +00001036
Chris Lattner51679082010-09-16 17:09:42 +00001037 // Produce a nice diagnostic if multiple values aren't handled.
1038 switch (UnhandledNames.size()) {
1039 case 0: break;
1040 case 1:
Chad Rosier02a84392012-08-10 17:56:09 +00001041 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001042 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
Chris Lattner51679082010-09-16 17:09:42 +00001043 << UnhandledNames[0];
1044 break;
1045 case 2:
Chad Rosier02a84392012-08-10 17:56:09 +00001046 Diag(CondExpr->getExprLoc(), TheDefaultStmt
David Blaikie60ac6382012-01-23 04:46:12 +00001047 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
Chris Lattner51679082010-09-16 17:09:42 +00001048 << UnhandledNames[0] << UnhandledNames[1];
1049 break;
1050 case 3:
David Blaikie60ac6382012-01-23 04:46:12 +00001051 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1052 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
Chris Lattner51679082010-09-16 17:09:42 +00001053 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1054 break;
1055 default:
David Blaikie60ac6382012-01-23 04:46:12 +00001056 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1057 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
Chris Lattner51679082010-09-16 17:09:42 +00001058 << (unsigned)UnhandledNames.size()
1059 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1060 break;
1061 }
Ted Kremenekc42f3452010-09-09 00:05:53 +00001062
1063 if (!hasCasesNotInSwitch)
Ted Kremenek02627a22010-09-09 06:53:59 +00001064 SS->setAllEnumCasesCovered();
Douglas Gregorbd6839732010-02-08 22:24:16 +00001065 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001066 }
Chris Lattner10cb5e52007-08-23 06:23:56 +00001067
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001068 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1069 diag::warn_empty_switch_body);
1070
Mike Stump87c57ac2009-05-16 07:39:55 +00001071 // FIXME: If the case list was broken is some way, we don't have a good system
1072 // to patch it up. Instead, just return the whole substmt as broken.
Chris Lattner10cb5e52007-08-23 06:23:56 +00001073 if (CaseListIsErroneous)
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001074 return StmtError();
1075
Sebastian Redl6a8002e2009-01-11 00:38:46 +00001076 return Owned(SS);
Chris Lattneraf8d5812006-11-10 05:07:45 +00001077}
1078
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001079void
1080Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1081 Expr *SrcExpr) {
1082 unsigned DIAG = diag::warn_not_in_enum_assignement;
Chad Rosier02a84392012-08-10 17:56:09 +00001083 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001084 == DiagnosticsEngine::Ignored)
1085 return;
Chad Rosier02a84392012-08-10 17:56:09 +00001086
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001087 if (const EnumType *ET = DstType->getAs<EnumType>())
1088 if (!Context.hasSameType(SrcType, DstType) &&
1089 SrcType->isIntegerType()) {
1090 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1091 SrcExpr->isIntegerConstantExpr(Context)) {
1092 // Get the bitwidth of the enum value before promotions.
1093 unsigned DstWith = Context.getIntWidth(DstType);
1094 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1095
1096 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1097 const EnumDecl *ED = ET->getDecl();
1098 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1099 EnumValsTy;
1100 EnumValsTy EnumVals;
Chad Rosier02a84392012-08-10 17:56:09 +00001101
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001102 // Gather all enum values, set their type and sort them,
1103 // allowing easier comparison with rhs constant.
1104 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1105 EDI != ED->enumerator_end(); ++EDI) {
1106 llvm::APSInt Val = EDI->getInitVal();
1107 AdjustAPSInt(Val, DstWith, DstIsSigned);
1108 EnumVals.push_back(std::make_pair(Val, *EDI));
1109 }
1110 if (EnumVals.empty())
1111 return;
1112 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1113 EnumValsTy::iterator EIend =
1114 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
Chad Rosier02a84392012-08-10 17:56:09 +00001115
Fariborz Jahanian268fec12012-07-17 18:00:08 +00001116 // See which case values aren't in enum.
1117 EnumValsTy::const_iterator EI = EnumVals.begin();
1118 while (EI != EIend && EI->first < RhsVal)
1119 EI++;
1120 if (EI == EIend || EI->first != RhsVal) {
1121 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1122 << DstType;
1123 }
1124 }
1125 }
1126}
1127
John McCalldadc5752010-08-24 06:29:42 +00001128StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
John McCallb268a282010-08-23 23:25:46 +00001130 Decl *CondVar, Stmt *Body) {
John McCalldadc5752010-08-24 06:29:42 +00001131 ExprResult CondResult(Cond.release());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001132
Douglas Gregor680f8612009-11-24 21:15:44 +00001133 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001134 if (CondVar) {
1135 ConditionVar = cast<VarDecl>(CondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001136 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001137 if (CondResult.isInvalid())
1138 return StmtError();
Douglas Gregor680f8612009-11-24 21:15:44 +00001139 }
John McCallb268a282010-08-23 23:25:46 +00001140 Expr *ConditionExpr = CondResult.take();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001141 if (!ConditionExpr)
1142 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
John McCallb268a282010-08-23 23:25:46 +00001144 DiagnoseUnusedExprResult(Body);
Mike Stump11289f42009-09-09 15:08:12 +00001145
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001146 if (isa<NullStmt>(Body))
1147 getCurCompoundScope().setHasEmptyLoopBodies();
1148
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001149 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
John McCallb268a282010-08-23 23:25:46 +00001150 Body, WhileLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001151}
1152
John McCalldadc5752010-08-24 06:29:42 +00001153StmtResult
John McCallb268a282010-08-23 23:25:46 +00001154Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
Chris Lattner815b70e2009-06-12 23:04:47 +00001155 SourceLocation WhileLoc, SourceLocation CondLParen,
John McCallb268a282010-08-23 23:25:46 +00001156 Expr *Cond, SourceLocation CondRParen) {
1157 assert(Cond && "ActOnDoStmt(): missing expression");
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001158
John Wiegley01296292011-04-08 18:41:53 +00001159 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1160 if (CondResult.isInvalid() || CondResult.isInvalid())
John McCalld5707ab2009-10-12 21:59:07 +00001161 return StmtError();
John Wiegley01296292011-04-08 18:41:53 +00001162 Cond = CondResult.take();
Steve Naroff86272ea2007-05-29 02:14:17 +00001163
John McCallacf0ee52010-10-08 02:01:28 +00001164 CheckImplicitConversions(Cond, DoLoc);
John Wiegley01296292011-04-08 18:41:53 +00001165 CondResult = MaybeCreateExprWithCleanups(Cond);
John McCallb268a282010-08-23 23:25:46 +00001166 if (CondResult.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001167 return StmtError();
John McCallb268a282010-08-23 23:25:46 +00001168 Cond = CondResult.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169
John McCallb268a282010-08-23 23:25:46 +00001170 DiagnoseUnusedExprResult(Body);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001171
John McCallb268a282010-08-23 23:25:46 +00001172 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001173}
1174
Richard Trieu451a5db2012-04-30 18:01:30 +00001175namespace {
1176 // This visitor will traverse a conditional statement and store all
1177 // the evaluated decls into a vector. Simple is set to true if none
1178 // of the excluded constructs are used.
1179 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1180 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1181 llvm::SmallVector<SourceRange, 10> &Ranges;
1182 bool Simple;
Richard Trieu451a5db2012-04-30 18:01:30 +00001183public:
1184 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1185
1186 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001187 llvm::SmallVector<SourceRange, 10> &Ranges) :
Richard Trieu451a5db2012-04-30 18:01:30 +00001188 Inherited(S.Context),
1189 Decls(Decls),
1190 Ranges(Ranges),
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001191 Simple(true) {}
Richard Trieu451a5db2012-04-30 18:01:30 +00001192
1193 bool isSimple() { return Simple; }
1194
1195 // Replaces the method in EvaluatedExprVisitor.
1196 void VisitMemberExpr(MemberExpr* E) {
1197 Simple = false;
1198 }
1199
1200 // Any Stmt not whitelisted will cause the condition to be marked complex.
1201 void VisitStmt(Stmt *S) {
1202 Simple = false;
1203 }
1204
1205 void VisitBinaryOperator(BinaryOperator *E) {
1206 Visit(E->getLHS());
1207 Visit(E->getRHS());
1208 }
1209
1210 void VisitCastExpr(CastExpr *E) {
1211 Visit(E->getSubExpr());
1212 }
1213
1214 void VisitUnaryOperator(UnaryOperator *E) {
1215 // Skip checking conditionals with derefernces.
1216 if (E->getOpcode() == UO_Deref)
1217 Simple = false;
1218 else
1219 Visit(E->getSubExpr());
1220 }
1221
1222 void VisitConditionalOperator(ConditionalOperator *E) {
1223 Visit(E->getCond());
1224 Visit(E->getTrueExpr());
1225 Visit(E->getFalseExpr());
1226 }
1227
1228 void VisitParenExpr(ParenExpr *E) {
1229 Visit(E->getSubExpr());
1230 }
1231
1232 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1233 Visit(E->getOpaqueValue()->getSourceExpr());
1234 Visit(E->getFalseExpr());
1235 }
1236
1237 void VisitIntegerLiteral(IntegerLiteral *E) { }
1238 void VisitFloatingLiteral(FloatingLiteral *E) { }
1239 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1240 void VisitCharacterLiteral(CharacterLiteral *E) { }
1241 void VisitGNUNullExpr(GNUNullExpr *E) { }
1242 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1243
1244 void VisitDeclRefExpr(DeclRefExpr *E) {
1245 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1246 if (!VD) return;
1247
1248 Ranges.push_back(E->getSourceRange());
1249
1250 Decls.insert(VD);
1251 }
1252
1253 }; // end class DeclExtractor
1254
1255 // DeclMatcher checks to see if the decls are used in a non-evauluated
Chad Rosier02a84392012-08-10 17:56:09 +00001256 // context.
Richard Trieu451a5db2012-04-30 18:01:30 +00001257 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1258 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1259 bool FoundDecl;
Richard Trieu451a5db2012-04-30 18:01:30 +00001260
1261public:
1262 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1263
1264 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1265 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1266 if (!Statement) return;
1267
1268 Visit(Statement);
1269 }
1270
1271 void VisitReturnStmt(ReturnStmt *S) {
1272 FoundDecl = true;
1273 }
1274
1275 void VisitBreakStmt(BreakStmt *S) {
1276 FoundDecl = true;
1277 }
1278
1279 void VisitGotoStmt(GotoStmt *S) {
1280 FoundDecl = true;
1281 }
1282
1283 void VisitCastExpr(CastExpr *E) {
1284 if (E->getCastKind() == CK_LValueToRValue)
1285 CheckLValueToRValueCast(E->getSubExpr());
1286 else
1287 Visit(E->getSubExpr());
1288 }
1289
1290 void CheckLValueToRValueCast(Expr *E) {
1291 E = E->IgnoreParenImpCasts();
1292
1293 if (isa<DeclRefExpr>(E)) {
1294 return;
1295 }
1296
1297 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1298 Visit(CO->getCond());
1299 CheckLValueToRValueCast(CO->getTrueExpr());
1300 CheckLValueToRValueCast(CO->getFalseExpr());
1301 return;
1302 }
1303
1304 if (BinaryConditionalOperator *BCO =
1305 dyn_cast<BinaryConditionalOperator>(E)) {
1306 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1307 CheckLValueToRValueCast(BCO->getFalseExpr());
1308 return;
1309 }
1310
1311 Visit(E);
1312 }
1313
1314 void VisitDeclRefExpr(DeclRefExpr *E) {
1315 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1316 if (Decls.count(VD))
1317 FoundDecl = true;
1318 }
1319
1320 bool FoundDeclInUse() { return FoundDecl; }
1321
1322 }; // end class DeclMatcher
1323
1324 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1325 Expr *Third, Stmt *Body) {
1326 // Condition is empty
1327 if (!Second) return;
1328
1329 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1330 Second->getLocStart())
1331 == DiagnosticsEngine::Ignored)
1332 return;
1333
1334 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1335 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1336 llvm::SmallVector<SourceRange, 10> Ranges;
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001337 DeclExtractor DE(S, Decls, Ranges);
Richard Trieu451a5db2012-04-30 18:01:30 +00001338 DE.Visit(Second);
1339
1340 // Don't analyze complex conditionals.
1341 if (!DE.isSimple()) return;
1342
1343 // No decls found.
1344 if (Decls.size() == 0) return;
1345
Richard Trieu0030f1d2012-05-04 03:01:54 +00001346 // Don't warn on volatile, static, or global variables.
Richard Trieu451a5db2012-04-30 18:01:30 +00001347 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1348 E = Decls.end();
1349 I != E; ++I)
Richard Trieu0030f1d2012-05-04 03:01:54 +00001350 if ((*I)->getType().isVolatileQualified() ||
1351 (*I)->hasGlobalStorage()) return;
Richard Trieu451a5db2012-04-30 18:01:30 +00001352
1353 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1354 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1355 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1356 return;
1357
1358 // Load decl names into diagnostic.
1359 if (Decls.size() > 4)
1360 PDiag << 0;
1361 else {
1362 PDiag << Decls.size();
1363 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1364 E = Decls.end();
1365 I != E; ++I)
1366 PDiag << (*I)->getDeclName();
1367 }
1368
1369 // Load SourceRanges into diagnostic if there is room.
1370 // Otherwise, load the SourceRange of the conditional expression.
1371 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1372 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1373 E = Ranges.end();
1374 I != E; ++I)
1375 PDiag << *I;
1376 else
1377 PDiag << Second->getSourceRange();
1378
1379 S.Diag(Ranges.begin()->getBegin(), PDiag);
1380 }
1381
1382} // end namespace
1383
John McCalldadc5752010-08-24 06:29:42 +00001384StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001385Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001386 Stmt *First, FullExprArg second, Decl *secondVar,
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001387 FullExprArg third,
John McCallb268a282010-08-23 23:25:46 +00001388 SourceLocation RParenLoc, Stmt *Body) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001389 if (!getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001390 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001391 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1392 // declare identifiers for objects having storage class 'auto' or
1393 // 'register'.
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001394 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1395 DI!=DE; ++DI) {
1396 VarDecl *VD = dyn_cast<VarDecl>(*DI);
John McCall1c9c3fd2010-10-15 04:57:14 +00001397 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001398 VD = 0;
1399 if (VD == 0)
1400 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1401 // FIXME: mark decl erroneous!
1402 }
Chris Lattner39f920f2007-08-28 05:03:08 +00001403 }
Steve Naroff86272ea2007-05-29 02:14:17 +00001404 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001405
Richard Trieu451a5db2012-04-30 18:01:30 +00001406 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1407
John McCalldadc5752010-08-24 06:29:42 +00001408 ExprResult SecondResult(second.release());
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001409 VarDecl *ConditionVar = 0;
John McCall48871652010-08-21 09:40:31 +00001410 if (secondVar) {
1411 ConditionVar = cast<VarDecl>(secondVar);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001412 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001413 if (SecondResult.isInvalid())
1414 return StmtError();
1415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001417 Expr *Third = third.release().takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418
Anders Carlsson1682af52009-08-01 01:39:59 +00001419 DiagnoseUnusedExprResult(First);
1420 DiagnoseUnusedExprResult(Third);
Anders Carlsson5c5f1602009-07-30 22:39:03 +00001421 DiagnoseUnusedExprResult(Body);
1422
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00001423 if (isa<NullStmt>(Body))
1424 getCurCompoundScope().setHasEmptyLoopBodies();
1425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001426 return Owned(new (Context) ForStmt(Context, First,
1427 SecondResult.take(), ConditionVar,
1428 Third, Body, ForLoc, LParenLoc,
Douglas Gregor27b98ea2010-06-21 23:44:13 +00001429 RParenLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00001430}
1431
John McCall34376a62010-12-04 03:47:34 +00001432/// In an Objective C collection iteration statement:
1433/// for (x in y)
1434/// x can be an arbitrary l-value expression. Bind it up as a
1435/// full-expression.
1436StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
John McCallbc153352012-03-30 05:43:39 +00001437 // Reduce placeholder expressions here. Note that this rejects the
1438 // use of pseudo-object l-values in this position.
1439 ExprResult result = CheckPlaceholderExpr(E);
1440 if (result.isInvalid()) return StmtError();
1441 E = result.take();
1442
John McCall34376a62010-12-04 03:47:34 +00001443 CheckImplicitConversions(E);
John McCallbc153352012-03-30 05:43:39 +00001444
1445 result = MaybeCreateExprWithCleanups(E);
1446 if (result.isInvalid()) return StmtError();
1447
1448 return Owned(static_cast<Stmt*>(result.take()));
John McCall34376a62010-12-04 03:47:34 +00001449}
1450
John McCall53848232011-07-27 01:07:15 +00001451ExprResult
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001452Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1453 if (!collection)
1454 return ExprError();
Chad Rosier02a84392012-08-10 17:56:09 +00001455
John McCall53848232011-07-27 01:07:15 +00001456 // Bail out early if we've got a type-dependent expression.
1457 if (collection->isTypeDependent()) return Owned(collection);
1458
1459 // Perform normal l-value conversion.
1460 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1461 if (result.isInvalid())
1462 return ExprError();
1463 collection = result.take();
1464
1465 // The operand needs to have object-pointer type.
1466 // TODO: should we do a contextual conversion?
1467 const ObjCObjectPointerType *pointerType =
1468 collection->getType()->getAs<ObjCObjectPointerType>();
1469 if (!pointerType)
1470 return Diag(forLoc, diag::err_collection_expr_type)
1471 << collection->getType() << collection->getSourceRange();
1472
1473 // Check that the operand provides
1474 // - countByEnumeratingWithState:objects:count:
1475 const ObjCObjectType *objectType = pointerType->getObjectType();
1476 ObjCInterfaceDecl *iface = objectType->getInterface();
1477
1478 // If we have a forward-declared type, we can't do this check.
Douglas Gregor4123a862011-11-14 22:10:01 +00001479 // Under ARC, it is an error not to have a forward-declared class.
Chad Rosier02a84392012-08-10 17:56:09 +00001480 if (iface &&
Douglas Gregor4123a862011-11-14 22:10:01 +00001481 RequireCompleteType(forLoc, QualType(objectType, 0),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001482 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001483 ? diag::err_arc_collection_forward
1484 : 0,
1485 collection)) {
John McCall53848232011-07-27 01:07:15 +00001486 // Otherwise, if we have any useful type information, check that
1487 // the type declares the appropriate method.
1488 } else if (iface || !objectType->qual_empty()) {
1489 IdentifierInfo *selectorIdents[] = {
1490 &Context.Idents.get("countByEnumeratingWithState"),
1491 &Context.Idents.get("objects"),
1492 &Context.Idents.get("count")
1493 };
1494 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1495
1496 ObjCMethodDecl *method = 0;
1497
1498 // If there's an interface, look in both the public and private APIs.
1499 if (iface) {
1500 method = iface->lookupInstanceMethod(selector);
Anna Zaksc77a3b12012-07-27 19:07:44 +00001501 if (!method) method = iface->lookupPrivateMethod(selector);
John McCall53848232011-07-27 01:07:15 +00001502 }
1503
1504 // Also check protocol qualifiers.
1505 if (!method)
1506 method = LookupMethodInQualifiedType(selector, pointerType,
1507 /*instance*/ true);
1508
1509 // If we didn't find it anywhere, give up.
1510 if (!method) {
1511 Diag(forLoc, diag::warn_collection_expr_type)
1512 << collection->getType() << selector << collection->getSourceRange();
1513 }
1514
1515 // TODO: check for an incompatible signature?
1516 }
1517
1518 // Wrap up any cleanups in the expression.
1519 return Owned(MaybeCreateExprWithCleanups(collection));
1520}
1521
John McCalldadc5752010-08-24 06:29:42 +00001522StmtResult
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001523Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1524 SourceLocation LParenLoc,
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001525 Stmt *First, Expr *collection,
1526 SourceLocation RParenLoc) {
Chad Rosier02a84392012-08-10 17:56:09 +00001527
1528 ExprResult CollectionExprResult =
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001529 CheckObjCForCollectionOperand(ForLoc, collection);
Chad Rosier02a84392012-08-10 17:56:09 +00001530
Fariborz Jahanian93977672008-01-10 20:33:58 +00001531 if (First) {
1532 QualType FirstType;
1533 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
Chris Lattner529efc72009-03-28 06:33:19 +00001534 if (!DS->isSingleDecl())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001535 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1536 diag::err_toomany_element_decls));
1537
John McCall31168b02011-06-15 23:02:42 +00001538 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1539 FirstType = D->getType();
Chris Lattner651d42d2008-11-20 06:38:18 +00001540 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1541 // declare identifiers for objects having storage class 'auto' or
1542 // 'register'.
John McCall31168b02011-06-15 23:02:42 +00001543 if (!D->hasLocalStorage())
1544 return StmtError(Diag(D->getLocation(),
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001545 diag::err_non_variable_decl_in_for));
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001546 } else {
Douglas Gregorf68a5082010-04-22 23:10:45 +00001547 Expr *FirstE = cast<Expr>(First);
John McCall086a4642010-11-24 05:12:34 +00001548 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
Sebastian Redlfbfaafc2009-01-16 23:28:06 +00001549 return StmtError(Diag(First->getLocStart(),
1550 diag::err_selector_element_not_lvalue)
1551 << First->getSourceRange());
1552
Mike Stump11289f42009-09-09 15:08:12 +00001553 FirstType = static_cast<Expr*>(First)->getType();
Anders Carlsson1ec2ccd2008-08-25 18:16:36 +00001554 }
Douglas Gregorf68a5082010-04-22 23:10:45 +00001555 if (!FirstType->isDependentType() &&
1556 !FirstType->isObjCObjectPointerType() &&
Fariborz Jahanian2e4a46b2009-08-14 21:53:27 +00001557 !FirstType->isBlockPointerType())
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001558 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1559 << FirstType << First->getSourceRange());
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001560 }
Chad Rosier02a84392012-08-10 17:56:09 +00001561
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001562 if (CollectionExprResult.isInvalid())
1563 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001564
1565 return Owned(new (Context) ObjCForCollectionStmt(First,
1566 CollectionExprResult.take(), 0,
Ted Kremenek5a201952009-02-07 01:47:29 +00001567 ForLoc, RParenLoc));
Fariborz Jahanian732b8c22008-01-03 17:55:25 +00001568}
Chris Lattneraf8d5812006-11-10 05:07:45 +00001569
Richard Smith02e85f32011-04-14 22:09:26 +00001570namespace {
1571
1572enum BeginEndFunction {
1573 BEF_begin,
1574 BEF_end
1575};
1576
1577/// Build a variable declaration for a for-range statement.
1578static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1579 QualType Type, const char *Name) {
1580 DeclContext *DC = SemaRef.CurContext;
1581 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1582 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1583 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1584 TInfo, SC_Auto, SC_None);
Richard Smith0c502d22011-04-18 15:49:25 +00001585 Decl->setImplicit();
Richard Smith02e85f32011-04-14 22:09:26 +00001586 return Decl;
1587}
1588
1589/// Finish building a variable declaration for a for-range statement.
1590/// \return true if an error occurs.
1591static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1592 SourceLocation Loc, int diag) {
1593 // Deduce the type for the iterator variable now rather than leaving it to
1594 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1595 TypeSourceInfo *InitTSI = 0;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00001596 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
Sebastian Redl09edce02012-01-23 22:09:39 +00001597 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1598 Sema::DAR_Failed)
Richard Smith02e85f32011-04-14 22:09:26 +00001599 SemaRef.Diag(Loc, diag) << Init->getType();
1600 if (!InitTSI) {
1601 Decl->setInvalidDecl();
1602 return true;
1603 }
1604 Decl->setTypeSourceInfo(InitTSI);
1605 Decl->setType(InitTSI->getType());
1606
John McCall31168b02011-06-15 23:02:42 +00001607 // In ARC, infer lifetime.
1608 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1609 // we're doing the equivalent of fast iteration.
Chad Rosier02a84392012-08-10 17:56:09 +00001610 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001611 SemaRef.inferObjCARCLifetime(Decl))
1612 Decl->setInvalidDecl();
1613
Richard Smith02e85f32011-04-14 22:09:26 +00001614 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1615 /*TypeMayContainAuto=*/false);
1616 SemaRef.FinalizeDeclaration(Decl);
Richard Smith0c502d22011-04-18 15:49:25 +00001617 SemaRef.CurContext->addHiddenDecl(Decl);
Richard Smith02e85f32011-04-14 22:09:26 +00001618 return false;
1619}
1620
1621/// Produce a note indicating which begin/end function was implicitly called
1622/// by a C++0x for-range statement. This is often not obvious from the code,
1623/// nor from the diagnostics produced when analysing the implicit expressions
1624/// required in a for-range statement.
1625void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1626 BeginEndFunction BEF) {
1627 CallExpr *CE = dyn_cast<CallExpr>(E);
1628 if (!CE)
1629 return;
1630 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1631 if (!D)
1632 return;
1633 SourceLocation Loc = D->getLocation();
1634
1635 std::string Description;
1636 bool IsTemplate = false;
1637 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1638 Description = SemaRef.getTemplateArgumentBindingsText(
1639 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1640 IsTemplate = true;
1641 }
1642
1643 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1644 << BEF << IsTemplate << Description << E->getType();
1645}
1646
1647/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1648/// given LookupResult is non-empty, it is assumed to describe a member which
1649/// will be invoked. Otherwise, the function will be found via argument
1650/// dependent lookup.
1651static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1652 SourceLocation Loc,
1653 VarDecl *Decl,
1654 BeginEndFunction BEF,
1655 const DeclarationNameInfo &NameInfo,
1656 LookupResult &MemberLookup,
1657 Expr *Range) {
1658 ExprResult CallExpr;
1659 if (!MemberLookup.empty()) {
1660 ExprResult MemberRef =
1661 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1662 /*IsPtr=*/false, CXXScopeSpec(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001663 /*TemplateKWLoc=*/SourceLocation(),
1664 /*FirstQualifierInScope=*/0,
1665 MemberLookup,
Richard Smith02e85f32011-04-14 22:09:26 +00001666 /*TemplateArgs=*/0);
1667 if (MemberRef.isInvalid())
1668 return ExprError();
1669 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1670 Loc, 0);
1671 if (CallExpr.isInvalid())
1672 return ExprError();
1673 } else {
1674 UnresolvedSet<0> FoundNames;
1675 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1676 // std is an associated namespace.
1677 UnresolvedLookupExpr *Fn =
1678 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1679 NestedNameSpecifierLoc(), NameInfo,
1680 /*NeedsADL=*/true, /*Overloaded=*/false,
1681 FoundNames.begin(), FoundNames.end(),
1682 /*LookInStdNamespace=*/true);
1683 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +00001684 0, /*AllowTypoCorrection=*/false);
Richard Smith02e85f32011-04-14 22:09:26 +00001685 if (CallExpr.isInvalid()) {
1686 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1687 << Range->getType();
1688 return ExprError();
1689 }
1690 }
1691 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1692 diag::err_for_range_iter_deduction_failure)) {
1693 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1694 return ExprError();
1695 }
1696 return CallExpr;
1697}
1698
1699}
1700
Fariborz Jahanian00213472012-07-06 19:04:04 +00001701static bool ObjCEnumerationCollection(Expr *Collection) {
1702 return !Collection->isTypeDependent()
1703 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1704}
1705
Richard Smith02e85f32011-04-14 22:09:26 +00001706/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1707///
1708/// C++0x [stmt.ranged]:
1709/// A range-based for statement is equivalent to
1710///
1711/// {
1712/// auto && __range = range-init;
1713/// for ( auto __begin = begin-expr,
1714/// __end = end-expr;
1715/// __begin != __end;
1716/// ++__begin ) {
1717/// for-range-declaration = *__begin;
1718/// statement
1719/// }
1720/// }
1721///
1722/// The body of the loop is not available yet, since it cannot be analysed until
1723/// we have determined the type of the for-range-declaration.
1724StmtResult
1725Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1726 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1727 SourceLocation RParenLoc) {
1728 if (!First || !Range)
1729 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00001730
Fariborz Jahanian00213472012-07-06 19:04:04 +00001731 if (ObjCEnumerationCollection(Range))
1732 return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1733 RParenLoc);
Richard Smith02e85f32011-04-14 22:09:26 +00001734
1735 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1736 assert(DS && "first part of for range not a decl stmt");
1737
1738 if (!DS->isSingleDecl()) {
1739 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1740 return StmtError();
1741 }
1742 if (DS->getSingleDecl()->isInvalidDecl())
1743 return StmtError();
1744
1745 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1746 return StmtError();
1747
1748 // Build auto && __range = range-init
1749 SourceLocation RangeLoc = Range->getLocStart();
1750 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1751 Context.getAutoRRefDeductType(),
1752 "__range");
1753 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1754 diag::err_for_range_deduction_failure))
1755 return StmtError();
1756
1757 // Claim the type doesn't contain auto: we've already done the checking.
1758 DeclGroupPtrTy RangeGroup =
1759 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1760 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1761 if (RangeDecl.isInvalid())
1762 return StmtError();
1763
1764 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1765 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1766 RParenLoc);
1767}
1768
1769/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1770StmtResult
1771Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1772 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1773 Expr *Inc, Stmt *LoopVarDecl,
1774 SourceLocation RParenLoc) {
1775 Scope *S = getCurScope();
1776
1777 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1778 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1779 QualType RangeVarType = RangeVar->getType();
1780
1781 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1782 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1783
1784 StmtResult BeginEndDecl = BeginEnd;
1785 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1786
1787 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1788 SourceLocation RangeLoc = RangeVar->getLocation();
1789
Ted Kremenekbed648e2011-10-10 22:36:28 +00001790 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1791
1792 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1793 VK_LValue, ColonLoc);
1794 if (BeginRangeRef.isInvalid())
1795 return StmtError();
1796
1797 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1798 VK_LValue, ColonLoc);
1799 if (EndRangeRef.isInvalid())
Richard Smith02e85f32011-04-14 22:09:26 +00001800 return StmtError();
1801
1802 QualType AutoType = Context.getAutoDeductType();
1803 Expr *Range = RangeVar->getInit();
1804 if (!Range)
1805 return StmtError();
1806 QualType RangeType = Range->getType();
1807
1808 if (RequireCompleteType(RangeLoc, RangeType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001809 diag::err_for_range_incomplete_type))
Richard Smith02e85f32011-04-14 22:09:26 +00001810 return StmtError();
1811
1812 // Build auto __begin = begin-expr, __end = end-expr.
1813 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1814 "__begin");
1815 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1816 "__end");
1817
1818 // Build begin-expr and end-expr and attach to __begin and __end variables.
1819 ExprResult BeginExpr, EndExpr;
1820 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1821 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1822 // __range + __bound, respectively, where __bound is the array bound. If
1823 // _RangeT is an array of unknown size or an array of incomplete type,
1824 // the program is ill-formed;
1825
1826 // begin-expr is __range.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001827 BeginExpr = BeginRangeRef;
1828 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
Richard Smith02e85f32011-04-14 22:09:26 +00001829 diag::err_for_range_iter_deduction_failure)) {
1830 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1831 return StmtError();
1832 }
1833
1834 // Find the array bound.
1835 ExprResult BoundExpr;
1836 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1837 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
Richard Trieu6a505ba2011-05-02 23:00:27 +00001838 Context.getPointerDiffType(),
1839 RangeLoc));
Richard Smith02e85f32011-04-14 22:09:26 +00001840 else if (const VariableArrayType *VAT =
1841 dyn_cast<VariableArrayType>(UnqAT))
1842 BoundExpr = VAT->getSizeExpr();
1843 else {
1844 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1845 // UnqAT is not incomplete and Range is not type-dependent.
David Blaikie83d382b2011-09-23 05:06:16 +00001846 llvm_unreachable("Unexpected array type in for-range");
Richard Smith02e85f32011-04-14 22:09:26 +00001847 }
1848
1849 // end-expr is __range + __bound.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001850 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
Richard Smith02e85f32011-04-14 22:09:26 +00001851 BoundExpr.get());
1852 if (EndExpr.isInvalid())
1853 return StmtError();
1854 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1855 diag::err_for_range_iter_deduction_failure)) {
1856 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1857 return StmtError();
1858 }
1859 } else {
1860 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1861 ColonLoc);
1862 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1863 ColonLoc);
1864
1865 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1866 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1867
1868 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1869 // - if _RangeT is a class type, the unqualified-ids begin and end are
1870 // looked up in the scope of class _RangeT as if by class member access
1871 // lookup (3.4.5), and if either (or both) finds at least one
1872 // declaration, begin-expr and end-expr are __range.begin() and
1873 // __range.end(), respectively;
1874 LookupQualifiedName(BeginMemberLookup, D);
1875 LookupQualifiedName(EndMemberLookup, D);
1876
1877 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1878 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1879 << RangeType << BeginMemberLookup.empty();
1880 return StmtError();
1881 }
1882 } else {
1883 // - otherwise, begin-expr and end-expr are begin(__range) and
1884 // end(__range), respectively, where begin and end are looked up with
1885 // argument-dependent lookup (3.4.2). For the purposes of this name
1886 // lookup, namespace std is an associated namespace.
1887 }
1888
1889 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1890 BEF_begin, BeginNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001891 BeginMemberLookup,
1892 BeginRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001893 if (BeginExpr.isInvalid())
1894 return StmtError();
1895
1896 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1897 BEF_end, EndNameInfo,
Ted Kremenekbed648e2011-10-10 22:36:28 +00001898 EndMemberLookup, EndRangeRef.get());
Richard Smith02e85f32011-04-14 22:09:26 +00001899 if (EndExpr.isInvalid())
1900 return StmtError();
1901 }
1902
1903 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1904 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1905 if (!Context.hasSameType(BeginType, EndType)) {
1906 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1907 << BeginType << EndType;
1908 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1909 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1910 }
1911
1912 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1913 // Claim the type doesn't contain auto: we've already done the checking.
1914 DeclGroupPtrTy BeginEndGroup =
1915 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1916 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1917
Ted Kremenekbed648e2011-10-10 22:36:28 +00001918 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1919 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
Richard Smith02e85f32011-04-14 22:09:26 +00001920 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001921 if (BeginRef.isInvalid())
1922 return StmtError();
1923
Richard Smith02e85f32011-04-14 22:09:26 +00001924 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1925 VK_LValue, ColonLoc);
Ted Kremenekbed648e2011-10-10 22:36:28 +00001926 if (EndRef.isInvalid())
1927 return StmtError();
Richard Smith02e85f32011-04-14 22:09:26 +00001928
1929 // Build and check __begin != __end expression.
1930 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1931 BeginRef.get(), EndRef.get());
1932 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1933 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1934 if (NotEqExpr.isInvalid()) {
1935 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1936 if (!Context.hasSameType(BeginType, EndType))
1937 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1938 return StmtError();
1939 }
1940
1941 // Build and check ++__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001942 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1943 VK_LValue, ColonLoc);
1944 if (BeginRef.isInvalid())
1945 return StmtError();
1946
Richard Smith02e85f32011-04-14 22:09:26 +00001947 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1948 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1949 if (IncrExpr.isInvalid()) {
1950 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1951 return StmtError();
1952 }
1953
1954 // Build and check *__begin expression.
Ted Kremenekbed648e2011-10-10 22:36:28 +00001955 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1956 VK_LValue, ColonLoc);
1957 if (BeginRef.isInvalid())
1958 return StmtError();
1959
Richard Smith02e85f32011-04-14 22:09:26 +00001960 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1961 if (DerefExpr.isInvalid()) {
1962 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1963 return StmtError();
1964 }
1965
1966 // Attach *__begin as initializer for VD.
1967 if (!LoopVar->isInvalidDecl()) {
1968 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1969 /*TypeMayContainAuto=*/true);
1970 if (LoopVar->isInvalidDecl())
1971 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1972 }
Richard Smithf9603352011-06-21 23:07:19 +00001973 } else {
1974 // The range is implicitly used as a placeholder when it is dependent.
1975 RangeVar->setUsed();
Richard Smith02e85f32011-04-14 22:09:26 +00001976 }
1977
1978 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1979 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1980 NotEqExpr.take(), IncrExpr.take(),
1981 LoopVarDS, /*Body=*/0, ForLoc,
1982 ColonLoc, RParenLoc));
1983}
1984
Chad Rosier02a84392012-08-10 17:56:09 +00001985/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001986/// statement.
1987StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1988 if (!S || !B)
1989 return StmtError();
1990 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
Chad Rosier02a84392012-08-10 17:56:09 +00001991
Fariborz Jahanian450bb6e2012-07-03 22:00:52 +00001992 ForStmt->setBody(B);
1993 return S;
1994}
1995
Richard Smith02e85f32011-04-14 22:09:26 +00001996/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1997/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1998/// body cannot be performed until after the type of the range variable is
1999/// determined.
2000StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2001 if (!S || !B)
2002 return StmtError();
2003
Fariborz Jahanian00213472012-07-06 19:04:04 +00002004 if (isa<ObjCForCollectionStmt>(S))
2005 return FinishObjCForCollectionStmt(S, B);
Chad Rosier02a84392012-08-10 17:56:09 +00002006
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00002007 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2008 ForStmt->setBody(B);
2009
2010 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2011 diag::warn_empty_range_based_for_body);
2012
Richard Smith02e85f32011-04-14 22:09:26 +00002013 return S;
2014}
2015
Chris Lattnercab02a62011-02-17 20:34:02 +00002016StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2017 SourceLocation LabelLoc,
2018 LabelDecl *TheDecl) {
2019 getCurFunction()->setHasBranchIntoScope();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002020 TheDecl->setUsed();
2021 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002022}
Chris Lattner1c310502007-05-31 06:00:00 +00002023
John McCalldadc5752010-08-24 06:29:42 +00002024StmtResult
Chris Lattner34d9a512009-04-19 01:04:21 +00002025Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
John McCallb268a282010-08-23 23:25:46 +00002026 Expr *E) {
Eli Friedman8d7ff402009-03-26 00:18:06 +00002027 // Convert operand to void*
Douglas Gregor30776d42009-05-16 00:20:29 +00002028 if (!E->isTypeDependent()) {
2029 QualType ETy = E->getType();
Chandler Carruth00216982010-01-31 10:26:25 +00002030 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
John Wiegley01296292011-04-08 18:41:53 +00002031 ExprResult ExprRes = Owned(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00002032 AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002033 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2034 if (ExprRes.isInvalid())
2035 return StmtError();
2036 E = ExprRes.take();
Chandler Carruth00216982010-01-31 10:26:25 +00002037 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
Douglas Gregor30776d42009-05-16 00:20:29 +00002038 return StmtError();
Eli Friedman9ccdb1d2012-01-31 22:47:07 +00002039 E = MaybeCreateExprWithCleanups(E);
Douglas Gregor30776d42009-05-16 00:20:29 +00002040 }
John McCalla95172b2010-08-01 00:26:45 +00002041
John McCallaab3e412010-08-25 08:40:02 +00002042 getCurFunction()->setHasIndirectGoto();
John McCalla95172b2010-08-01 00:26:45 +00002043
Douglas Gregor30776d42009-05-16 00:20:29 +00002044 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002045}
2046
John McCalldadc5752010-08-24 06:29:42 +00002047StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002048Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002049 Scope *S = CurScope->getContinueParent();
2050 if (!S) {
2051 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002052 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002053 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002054
Ted Kremenek5a201952009-02-07 01:47:29 +00002055 return Owned(new (Context) ContinueStmt(ContinueLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002056}
2057
John McCalldadc5752010-08-24 06:29:42 +00002058StmtResult
Steve Naroff66356bd2007-09-16 14:56:35 +00002059Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
Chris Lattnereaafe1222006-11-10 05:17:58 +00002060 Scope *S = CurScope->getBreakParent();
2061 if (!S) {
2062 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
Sebastian Redl573feed2009-01-18 13:19:59 +00002063 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
Chris Lattnereaafe1222006-11-10 05:17:58 +00002064 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002065
Ted Kremenek5a201952009-02-07 01:47:29 +00002066 return Owned(new (Context) BreakStmt(BreakLoc));
Chris Lattneraf8d5812006-11-10 05:07:45 +00002067}
2068
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069/// \brief Determine whether the given expression is a candidate for
Douglas Gregor5d369002011-01-21 18:05:27 +00002070/// copy elision in either a return statement or a throw expression.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002071///
Douglas Gregor5d369002011-01-21 18:05:27 +00002072/// \param ReturnType If we're determining the copy elision candidate for
2073/// a return statement, this is the return type of the function. If we're
2074/// determining the copy elision candidate for a throw expression, this will
2075/// be a NULL type.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002076///
Douglas Gregor5d369002011-01-21 18:05:27 +00002077/// \param E The expression being returned from the function or block, or
2078/// being thrown.
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002079///
Douglas Gregor86394412011-05-20 15:00:53 +00002080/// \param AllowFunctionParameter Whether we allow function parameters to
2081/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2082/// we re-use this logic to determine whether we should try to move as part of
2083/// a return or throw (which does allow function parameters).
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002084///
2085/// \returns The NRVO candidate variable, if the return statement may use the
2086/// NRVO, or NULL if there is no such candidate.
Douglas Gregor5d369002011-01-21 18:05:27 +00002087const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2088 Expr *E,
2089 bool AllowFunctionParameter) {
2090 QualType ExprType = E->getType();
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002091 // - in a return statement in a function with ...
2092 // ... a class return type ...
Douglas Gregor5d369002011-01-21 18:05:27 +00002093 if (!ReturnType.isNull()) {
2094 if (!ReturnType->isRecordType())
2095 return 0;
2096 // ... the same cv-unqualified type as the function return type ...
2097 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2098 return 0;
2099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
2101 // ... the expression is the name of a non-volatile automatic object
Douglas Gregor5d369002011-01-21 18:05:27 +00002102 // (other than a function or catch-clause parameter)) ...
2103 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
Nico Weber13253842012-07-11 22:50:15 +00002104 if (!DR || DR->refersToEnclosingLocal())
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002105 return 0;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002106 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2107 if (!VD)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002108 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002109
John McCall03318c12011-11-11 03:57:31 +00002110 // ...object (other than a function or catch-clause parameter)...
2111 if (VD->getKind() != Decl::Var &&
2112 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2113 return 0;
2114 if (VD->isExceptionVariable()) return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115
John McCall03318c12011-11-11 03:57:31 +00002116 // ...automatic...
2117 if (!VD->hasLocalStorage()) return 0;
2118
2119 // ...non-volatile...
2120 if (VD->getType().isVolatileQualified()) return 0;
2121 if (VD->getType()->isReferenceType()) return 0;
2122
2123 // __block variables can't be allocated in a way that permits NRVO.
2124 if (VD->hasAttr<BlocksAttr>()) return 0;
2125
2126 // Variables with higher required alignment than their type's ABI
2127 // alignment cannot use NRVO.
2128 if (VD->hasAttr<AlignedAttr>() &&
2129 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2130 return 0;
2131
2132 return VD;
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002133}
2134
Douglas Gregor626fbed2011-01-21 21:08:57 +00002135/// \brief Perform the initialization of a potentially-movable value, which
2136/// is the result of return value.
Douglas Gregorf282a762011-01-21 19:38:21 +00002137///
2138/// This routine implements C++0x [class.copy]p33, which attempts to treat
2139/// returned lvalues as rvalues in certain cases (to prefer move construction),
2140/// then falls back to treating them as lvalues if that failed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141ExprResult
Douglas Gregor626fbed2011-01-21 21:08:57 +00002142Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2143 const VarDecl *NRVOCandidate,
2144 QualType ResultType,
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002145 Expr *Value,
2146 bool AllowNRVO) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002147 // C++0x [class.copy]p33:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148 // When the criteria for elision of a copy operation are met or would
2149 // be met save for the fact that the source object is a function
2150 // parameter, and the object to be copied is designated by an lvalue,
Douglas Gregorf282a762011-01-21 19:38:21 +00002151 // overload resolution to select the constructor for the copy is first
2152 // performed as if the object were designated by an rvalue.
Douglas Gregorf282a762011-01-21 19:38:21 +00002153 ExprResult Res = ExprError();
Douglas Gregor53e191ed2011-07-06 22:04:06 +00002154 if (AllowNRVO &&
2155 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002156 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002157 Value->getType(), CK_NoOp, Value, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158
Douglas Gregorf282a762011-01-21 19:38:21 +00002159 Expr *InitExpr = &AsRvalue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002160 InitializationKind Kind
Douglas Gregor626fbed2011-01-21 21:08:57 +00002161 = InitializationKind::CreateCopy(Value->getLocStart(),
2162 Value->getLocStart());
2163 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
2165 // [...] If overload resolution fails, or if the type of the first
Douglas Gregorf282a762011-01-21 19:38:21 +00002166 // parameter of the selected constructor is not an rvalue reference
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002167 // to the object's type (possibly cv-qualified), overload resolution
Douglas Gregorf282a762011-01-21 19:38:21 +00002168 // is performed again, considering the object as an lvalue.
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002169 if (Seq) {
Douglas Gregorf282a762011-01-21 19:38:21 +00002170 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2171 StepEnd = Seq.step_end();
2172 Step != StepEnd; ++Step) {
Sebastian Redlc7ca5872011-06-05 12:23:28 +00002173 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
Douglas Gregorf282a762011-01-21 19:38:21 +00002174 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
2176 CXXConstructorDecl *Constructor
Douglas Gregorf282a762011-01-21 19:38:21 +00002177 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002178
Douglas Gregorf282a762011-01-21 19:38:21 +00002179 const RValueReferenceType *RRefType
Douglas Gregor626fbed2011-01-21 21:08:57 +00002180 = Constructor->getParamDecl(0)->getType()
2181 ->getAs<RValueReferenceType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182
Douglas Gregorf282a762011-01-21 19:38:21 +00002183 // If we don't meet the criteria, break out now.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184 if (!RRefType ||
Douglas Gregor626fbed2011-01-21 21:08:57 +00002185 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2186 Context.getTypeDeclType(Constructor->getParent())))
Douglas Gregorf282a762011-01-21 19:38:21 +00002187 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
Douglas Gregorf282a762011-01-21 19:38:21 +00002189 // Promote "AsRvalue" to the heap, since we now need this
2190 // expression node to persist.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002191 Value = ImplicitCastExpr::Create(Context, Value->getType(),
Richard Smith9dd6e8f2012-05-15 05:04:02 +00002192 CK_NoOp, Value, 0, VK_XValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193
Douglas Gregorf282a762011-01-21 19:38:21 +00002194 // Complete type-checking the initialization of the return type
2195 // using the constructor we found.
Douglas Gregor626fbed2011-01-21 21:08:57 +00002196 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
Douglas Gregorf282a762011-01-21 19:38:21 +00002197 }
2198 }
2199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200
Douglas Gregorf282a762011-01-21 19:38:21 +00002201 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202 // above, or overload resolution failed. Either way, we need to try
Douglas Gregorf282a762011-01-21 19:38:21 +00002203 // (again) now with the return value expression as written.
2204 if (Res.isInvalid())
Douglas Gregor626fbed2011-01-21 21:08:57 +00002205 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206
Douglas Gregorf282a762011-01-21 19:38:21 +00002207 return Res;
2208}
2209
Eli Friedman34b49062012-01-26 03:00:14 +00002210/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2211/// for capturing scopes.
Steve Naroffc540d662008-09-03 18:15:37 +00002212///
John McCalldadc5752010-08-24 06:29:42 +00002213StmtResult
Eli Friedman34b49062012-01-26 03:00:14 +00002214Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2215 // If this is the first return we've seen, infer the return type.
2216 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2217 // rules which allows multiple return statements.
2218 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
Jordan Rosed39e5f12012-07-02 21:19:23 +00002219 QualType FnRetType = CurCap->ReturnType;
2220
2221 // For blocks/lambdas with implicit return types, we check each return
2222 // statement individually, and deduce the common return type when the block
2223 // or lambda is completed.
Eli Friedman34b49062012-01-26 03:00:14 +00002224 if (CurCap->HasImplicitReturnType) {
Douglas Gregor940a5502012-02-09 18:40:39 +00002225 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
John Wiegley01296292011-04-08 18:41:53 +00002226 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2227 if (Result.isInvalid())
2228 return StmtError();
2229 RetValExp = Result.take();
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002230
Jordan Rosed39e5f12012-07-02 21:19:23 +00002231 if (!RetValExp->isTypeDependent())
2232 FnRetType = RetValExp->getType();
2233 else
2234 FnRetType = CurCap->ReturnType = Context.DependentTy;
Chad Rosier02a84392012-08-10 17:56:09 +00002235 } else {
Douglas Gregor940a5502012-02-09 18:40:39 +00002236 if (RetValExp) {
2237 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2238 // initializer list, because it is not an expression (even
2239 // though we represent it as one). We still deduce 'void'.
2240 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2241 << RetValExp->getSourceRange();
2242 }
2243
Jordan Rosed39e5f12012-07-02 21:19:23 +00002244 FnRetType = Context.VoidTy;
Fariborz Jahanian5c12ca82011-12-03 23:53:56 +00002245 }
Jordan Rosed39e5f12012-07-02 21:19:23 +00002246
2247 // Although we'll properly infer the type of the block once it's completed,
2248 // make sure we provide a return type now for better error recovery.
2249 if (CurCap->ReturnType.isNull())
2250 CurCap->ReturnType = FnRetType;
Steve Naroffc540d662008-09-03 18:15:37 +00002251 }
Eli Friedman34b49062012-01-26 03:00:14 +00002252 assert(!FnRetType.isNull());
Sebastian Redl573feed2009-01-18 13:19:59 +00002253
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002254 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
Eli Friedman34b49062012-01-26 03:00:14 +00002255 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2256 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2257 return StmtError();
2258 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +00002259 } else {
2260 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2261 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2262 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2263 return StmtError();
2264 }
2265 }
Mike Stump56ed2ea2009-04-29 21:40:37 +00002266
Steve Naroffc540d662008-09-03 18:15:37 +00002267 // Otherwise, verify that this result type matches the previous one. We are
2268 // pickier with blocks than for normal functions because we don't have GCC
2269 // compatibility to worry about here.
John McCall75f92b52011-08-17 21:34:14 +00002270 const VarDecl *NRVOCandidate = 0;
John McCall5500ef22011-08-17 22:09:46 +00002271 if (FnRetType->isDependentType()) {
2272 // Delay processing for now. TODO: there are lots of dependent
2273 // types we can conclusively prove aren't void.
2274 } else if (FnRetType->isVoidType()) {
Sebastian Redl74b173e2012-02-22 17:38:04 +00002275 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002276 !(getLangOpts().CPlusPlus &&
John McCall5500ef22011-08-17 22:09:46 +00002277 (RetValExp->isTypeDependent() ||
2278 RetValExp->getType()->isVoidType()))) {
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002279 if (!getLangOpts().CPlusPlus &&
2280 RetValExp->getType()->isVoidType())
Fariborz Jahanian0740ed92012-03-21 20:28:39 +00002281 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
Fariborz Jahanian3ba24ba2012-03-21 16:45:13 +00002282 else {
2283 Diag(ReturnLoc, diag::err_return_block_has_expr);
2284 RetValExp = 0;
2285 }
Steve Naroffc540d662008-09-03 18:15:37 +00002286 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002287 } else if (!RetValExp) {
John McCall5500ef22011-08-17 22:09:46 +00002288 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2289 } else if (!RetValExp->isTypeDependent()) {
2290 // we have a non-void block with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002291
John McCall5500ef22011-08-17 22:09:46 +00002292 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2293 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2294 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002295
John McCall5500ef22011-08-17 22:09:46 +00002296 // In C++ the return statement is handled via a copy initialization.
2297 // the C version of which boils down to CheckSingleAssignmentConstraints.
2298 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2299 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2300 FnRetType,
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00002301 NRVOCandidate != 0);
John McCall5500ef22011-08-17 22:09:46 +00002302 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2303 FnRetType, RetValExp);
2304 if (Res.isInvalid()) {
2305 // FIXME: Cleanup temporaries here, anyway?
2306 return StmtError();
Anders Carlsson6f923f82010-01-29 18:30:20 +00002307 }
John McCall5500ef22011-08-17 22:09:46 +00002308 RetValExp = Res.take();
2309 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Steve Naroffc540d662008-09-03 18:15:37 +00002310 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002311
John McCall75f92b52011-08-17 21:34:14 +00002312 if (RetValExp) {
2313 CheckImplicitConversions(RetValExp, ReturnLoc);
2314 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2315 }
John McCall5500ef22011-08-17 22:09:46 +00002316 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2317 NRVOCandidate);
John McCall75f92b52011-08-17 21:34:14 +00002318
Jordan Rosed39e5f12012-07-02 21:19:23 +00002319 // If we need to check for the named return value optimization,
2320 // or if we need to infer the return type,
2321 // save the return statement in our scope for later processing.
2322 if (CurCap->HasImplicitReturnType ||
2323 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2324 !CurContext->isDependentContext()))
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002325 FunctionScopes.back()->Returns.push_back(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002327 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00002328}
Chris Lattneraf8d5812006-11-10 05:07:45 +00002329
John McCalldadc5752010-08-24 06:29:42 +00002330StmtResult
John McCallb268a282010-08-23 23:25:46 +00002331Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
Douglas Gregor4385d8b2011-05-20 15:32:55 +00002332 // Check for unexpanded parameter packs.
2333 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2334 return StmtError();
Chad Rosier02a84392012-08-10 17:56:09 +00002335
Eli Friedman34b49062012-01-26 03:00:14 +00002336 if (isa<CapturingScopeInfo>(getCurFunction()))
2337 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
Sebastian Redl573feed2009-01-18 13:19:59 +00002338
Chris Lattner79413952008-12-04 23:50:19 +00002339 QualType FnRetType;
Eli Friedman410fc7a2012-03-30 01:13:43 +00002340 QualType RelatedRetType;
Mike Stumpd00bc1a2009-04-29 00:43:21 +00002341 if (const FunctionDecl *FD = getCurFunctionDecl()) {
Chris Lattner79413952008-12-04 23:50:19 +00002342 FnRetType = FD->getResultType();
John McCallab26cfa2010-02-05 21:31:56 +00002343 if (FD->hasAttr<NoReturnAttr>() ||
2344 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Chris Lattner6e127a62009-05-31 19:32:13 +00002345 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
Eli Friedmande958782012-01-05 00:49:17 +00002346 << FD->getDeclName();
Douglas Gregor33823722011-06-11 01:09:30 +00002347 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Eli Friedman410fc7a2012-03-30 01:13:43 +00002348 FnRetType = MD->getResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00002349 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2350 // In the implementation of a method with a related return type, the
Chad Rosier02a84392012-08-10 17:56:09 +00002351 // type used to type-check the validity of return statements within the
Douglas Gregor33823722011-06-11 01:09:30 +00002352 // method body is a pointer to the type of the class being implemented.
Eli Friedman410fc7a2012-03-30 01:13:43 +00002353 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2354 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
Douglas Gregor33823722011-06-11 01:09:30 +00002355 }
2356 } else // If we don't have a function/method context, bail.
Steve Narofff3833d72009-03-03 00:45:38 +00002357 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002358
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002359 ReturnStmt *Result = 0;
Chris Lattner9bad62c2008-01-04 18:04:52 +00002360 if (FnRetType->isVoidType()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002361 if (RetValExp) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002362 if (isa<InitListExpr>(RetValExp)) {
2363 // We simply never allow init lists as the return value of void
2364 // functions. This is compatible because this was never allowed before,
2365 // so there's no legacy code to deal with.
2366 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2367 int FunctionKind = 0;
2368 if (isa<ObjCMethodDecl>(CurDecl))
2369 FunctionKind = 1;
2370 else if (isa<CXXConstructorDecl>(CurDecl))
2371 FunctionKind = 2;
2372 else if (isa<CXXDestructorDecl>(CurDecl))
2373 FunctionKind = 3;
2374
2375 Diag(ReturnLoc, diag::err_return_init_list)
2376 << CurDecl->getDeclName() << FunctionKind
2377 << RetValExp->getSourceRange();
2378
2379 // Drop the expression.
2380 RetValExp = 0;
2381 } else if (!RetValExp->isTypeDependent()) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002382 // C99 6.8.6.4p1 (ext_ since GCC warns)
2383 unsigned D = diag::ext_return_has_expr;
2384 if (RetValExp->getType()->isVoidType())
2385 D = diag::ext_return_has_void_expr;
2386 else {
2387 ExprResult Result = Owned(RetValExp);
2388 Result = IgnoredValueConversions(Result.take());
2389 if (Result.isInvalid())
2390 return StmtError();
2391 RetValExp = Result.take();
2392 RetValExp = ImpCastExprToType(RetValExp,
2393 Context.VoidTy, CK_ToVoid).take();
2394 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002395
Nick Lewycky1be750a2011-06-01 07:44:31 +00002396 // return (some void expression); is legal in C++.
2397 if (D != diag::ext_return_has_void_expr ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002398 !getLangOpts().CPlusPlus) {
Nick Lewycky1be750a2011-06-01 07:44:31 +00002399 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002400
2401 int FunctionKind = 0;
2402 if (isa<ObjCMethodDecl>(CurDecl))
2403 FunctionKind = 1;
2404 else if (isa<CXXConstructorDecl>(CurDecl))
2405 FunctionKind = 2;
2406 else if (isa<CXXDestructorDecl>(CurDecl))
2407 FunctionKind = 3;
2408
Nick Lewycky1be750a2011-06-01 07:44:31 +00002409 Diag(ReturnLoc, D)
Chandler Carruth1406d6c2011-06-30 08:56:22 +00002410 << CurDecl->getDeclName() << FunctionKind
Nick Lewycky1be750a2011-06-01 07:44:31 +00002411 << RetValExp->getSourceRange();
2412 }
Chris Lattner0cb00d62008-12-18 02:03:48 +00002413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
Sebastian Redleef474c2012-02-22 10:50:08 +00002415 if (RetValExp) {
2416 CheckImplicitConversions(RetValExp, ReturnLoc);
2417 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2418 }
Steve Naroff6f49f5d2007-05-29 14:23:36 +00002419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002420
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002421 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2422 } else if (!RetValExp && !FnRetType->isDependentType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002423 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2424 // C99 6.8.6.4p1 (ext_ since GCC warns)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002425 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002426
2427 if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere3d20d92008-11-23 21:45:46 +00002428 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002429 else
Chris Lattnere3d20d92008-11-23 21:45:46 +00002430 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002431 Result = new (Context) ReturnStmt(ReturnLoc);
2432 } else {
2433 const VarDecl *NRVOCandidate = 0;
2434 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2435 // we have a non-void function with an expression, continue checking
Sebastian Redl573feed2009-01-18 13:19:59 +00002436
Eli Friedman410fc7a2012-03-30 01:13:43 +00002437 if (!RelatedRetType.isNull()) {
2438 // If we have a related result type, perform an extra conversion here.
2439 // FIXME: The diagnostics here don't really describe what is happening.
2440 InitializedEntity Entity =
2441 InitializedEntity::InitializeTemporary(RelatedRetType);
Chad Rosiercc6a9082012-06-20 18:51:04 +00002442
Eli Friedman410fc7a2012-03-30 01:13:43 +00002443 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2444 RetValExp);
2445 if (Res.isInvalid()) {
2446 // FIXME: Cleanup temporaries here, anyway?
2447 return StmtError();
2448 }
2449 RetValExp = Res.takeAs<Expr>();
2450 }
2451
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002452 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2453 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2454 // function return.
Sebastian Redl573feed2009-01-18 13:19:59 +00002455
John McCallfa272342011-06-16 23:24:51 +00002456 // In C++ the return statement is handled via a copy initialization,
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002457 // the C version of which boils down to CheckSingleAssignmentConstraints.
Douglas Gregor5d369002011-01-21 18:05:27 +00002458 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002460 FnRetType,
Francois Pichetfbf7e172011-06-02 00:47:27 +00002461 NRVOCandidate != 0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002462 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
Douglas Gregor626fbed2011-01-21 21:08:57 +00002463 FnRetType, RetValExp);
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002464 if (Res.isInvalid()) {
2465 // FIXME: Cleanup temporaries here, anyway?
2466 return StmtError();
2467 }
Sebastian Redl573feed2009-01-18 13:19:59 +00002468
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002469 RetValExp = Res.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470 if (RetValExp)
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002471 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002473
John McCallacf0ee52010-10-08 02:01:28 +00002474 if (RetValExp) {
2475 CheckImplicitConversions(RetValExp, ReturnLoc);
John McCall5d413782010-12-06 08:20:24 +00002476 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
John McCallacf0ee52010-10-08 02:01:28 +00002477 }
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002478 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
Douglas Gregor4619e432008-12-05 23:32:09 +00002479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
2481 // If we need to check for the named return value optimization, save the
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002482 // return statement in our scope for later processing.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002483 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002484 !CurContext->isDependentContext())
2485 FunctionScopes.back()->Returns.push_back(Result);
Chad Rosiercc6a9082012-06-20 18:51:04 +00002486
Douglas Gregor6fd1b182010-05-15 06:01:05 +00002487 return Owned(Result);
Chris Lattneraf8d5812006-11-10 05:07:45 +00002488}
2489
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002490/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2491/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2492/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2493/// provide a strong guidance to not use it.
2494///
2495/// This method checks to see if the argument is an acceptable l-value and
2496/// returns false if it is a case we can handle.
2497static bool CheckAsmLValue(const Expr *E, Sema &S) {
Anders Carlssonaaeef072010-01-24 05:50:09 +00002498 // Type dependent expressions will be checked during instantiation.
2499 if (E->isTypeDependent())
2500 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002501
John McCall086a4642010-11-24 05:12:34 +00002502 if (E->isLValue())
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002503 return false; // Cool, this is an lvalue.
2504
2505 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2506 // are supposed to allow.
2507 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
John McCall086a4642010-11-24 05:12:34 +00002508 if (E != E2 && E2->isLValue()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002509 if (!S.getLangOpts().HeinousExtensions)
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002510 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2511 << E->getSourceRange();
2512 else
2513 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2514 << E->getSourceRange();
2515 // Accept, even if we emitted an error diagnostic.
2516 return false;
2517 }
2518
2519 // None of the above, just randomly invalid non-lvalue.
2520 return true;
2521}
2522
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002523/// isOperandMentioned - Return true if the specified operand # is mentioned
2524/// anywhere in the decomposed asm string.
Chad Rosier02a84392012-08-10 17:56:09 +00002525static bool isOperandMentioned(unsigned OpNo,
Chris Lattner54b16772011-07-23 17:14:25 +00002526 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002527 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2528 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2529 if (!Piece.isOperand()) continue;
Chad Rosiercc6a9082012-06-20 18:51:04 +00002530
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002531 // If this is a reference to the input and if the input was the smaller
2532 // one, then we have to reject this asm.
2533 if (Piece.getOperandNo() == OpNo)
2534 return true;
2535 }
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002536 return false;
2537}
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002538
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002539StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2540 bool IsVolatile, unsigned NumOutputs,
2541 unsigned NumInputs, IdentifierInfo **Names,
2542 MultiExprArg constraints, MultiExprArg exprs,
2543 Expr *asmString, MultiExprArg clobbers,
2544 SourceLocation RParenLoc, bool MSAsm) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002545 unsigned NumClobbers = clobbers.size();
2546 StringLiteral **Constraints =
2547 reinterpret_cast<StringLiteral**>(constraints.get());
John McCallb268a282010-08-23 23:25:46 +00002548 Expr **Exprs = exprs.get();
2549 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Sebastian Redl24b8e152009-01-18 16:53:17 +00002550 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2551
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002552 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
Mike Stump11289f42009-09-09 15:08:12 +00002553
Chris Lattner496acc12008-08-18 19:55:17 +00002554 // The parser verifies that there is a string literal here.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002555 if (!AsmString->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002556 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2557 << AsmString->getSourceRange());
2558
Chris Lattner496acc12008-08-18 19:55:17 +00002559 for (unsigned i = 0; i != NumOutputs; i++) {
2560 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002561 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002562 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2563 << Literal->getSourceRange());
2564
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002565 StringRef OutputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002566 if (Names[i])
2567 OutputName = Names[i]->getName();
2568
2569 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002570 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002571 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002572 diag::err_asm_invalid_output_constraint)
2573 << Info.getConstraintStr());
Sebastian Redl24b8e152009-01-18 16:53:17 +00002574
Anders Carlssonf511f642007-11-27 04:11:28 +00002575 // Check that the output exprs are valid lvalues.
Eli Friedman47e78572009-05-03 07:49:42 +00002576 Expr *OutputExpr = Exprs[i];
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002577 if (CheckAsmLValue(OutputExpr, *this)) {
Eli Friedman47e78572009-05-03 07:49:42 +00002578 return StmtError(Diag(OutputExpr->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002579 diag::err_asm_invalid_lvalue_in_output)
Eli Friedman47e78572009-05-03 07:49:42 +00002580 << OutputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Chris Lattnerd9725f72009-04-26 07:16:29 +00002583 OutputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002584 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002585
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner34b51e82009-05-03 05:55:43 +00002587
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002588 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
Chris Lattner496acc12008-08-18 19:55:17 +00002589 StringLiteral *Literal = Constraints[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002590 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002591 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2592 << Literal->getSourceRange());
2593
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002594 StringRef InputName;
Anders Carlsson9a020f92010-01-30 22:25:16 +00002595 if (Names[i])
2596 InputName = Names[i]->getName();
2597
2598 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002599 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattnerc16d4762009-04-26 17:57:12 +00002600 NumOutputs, Info)) {
Sebastian Redl24b8e152009-01-18 16:53:17 +00002601 return StmtError(Diag(Literal->getLocStart(),
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002602 diag::err_asm_invalid_input_constraint)
2603 << Info.getConstraintStr());
Anders Carlssonf511f642007-11-27 04:11:28 +00002604 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002605
Eli Friedman47e78572009-05-03 07:49:42 +00002606 Expr *InputExpr = Exprs[i];
Sebastian Redl24b8e152009-01-18 16:53:17 +00002607
Anders Carlsson224fca82009-01-20 20:49:22 +00002608 // Only allow void types for memory constraints.
Chris Lattnerd9725f72009-04-26 07:16:29 +00002609 if (Info.allowsMemory() && !Info.allowsRegister()) {
Chris Lattnercda4d7e2009-03-13 17:38:01 +00002610 if (CheckAsmLValue(InputExpr, *this))
Eli Friedman47e78572009-05-03 07:49:42 +00002611 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002612 diag::err_asm_invalid_lvalue_in_input)
Chris Lattnerc3f4c7b2009-04-26 17:19:08 +00002613 << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002614 << InputExpr->getSourceRange());
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002615 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002616
Chris Lattnerd9725f72009-04-26 07:16:29 +00002617 if (Info.allowsRegister()) {
Anders Carlsson224fca82009-01-20 20:49:22 +00002618 if (InputExpr->getType()->isVoidType()) {
Eli Friedman47e78572009-05-03 07:49:42 +00002619 return StmtError(Diag(InputExpr->getLocStart(),
Anders Carlsson224fca82009-01-20 20:49:22 +00002620 diag::err_asm_invalid_type_in_input)
Mike Stump11289f42009-09-09 15:08:12 +00002621 << InputExpr->getType() << Info.getConstraintStr()
Eli Friedman47e78572009-05-03 07:49:42 +00002622 << InputExpr->getSourceRange());
Anders Carlsson224fca82009-01-20 20:49:22 +00002623 }
Anders Carlsson224fca82009-01-20 20:49:22 +00002624 }
Mike Stump11289f42009-09-09 15:08:12 +00002625
John Wiegley01296292011-04-08 18:41:53 +00002626 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2627 if (Result.isInvalid())
2628 return StmtError();
Mike Stump11289f42009-09-09 15:08:12 +00002629
John Wiegley01296292011-04-08 18:41:53 +00002630 Exprs[i] = Result.take();
Chris Lattner34b51e82009-05-03 05:55:43 +00002631 InputConstraintInfos.push_back(Info);
Anders Carlsson80a5ea32007-11-23 19:43:50 +00002632 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002633
Anders Carlsson290aa852007-11-25 00:25:21 +00002634 // Check that the clobbers are valid.
Chris Lattner496acc12008-08-18 19:55:17 +00002635 for (unsigned i = 0; i != NumClobbers; i++) {
2636 StringLiteral *Literal = Clobbers[i];
Douglas Gregorfb65e592011-07-27 05:40:30 +00002637 if (!Literal->isAscii())
Sebastian Redl24b8e152009-01-18 16:53:17 +00002638 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2639 << Literal->getSourceRange());
2640
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641 StringRef Clobber = Literal->getString();
Sebastian Redl24b8e152009-01-18 16:53:17 +00002642
Douglas Gregore8bbc122011-09-02 00:18:52 +00002643 if (!Context.getTargetInfo().isValidClobber(Clobber))
Sebastian Redl24b8e152009-01-18 16:53:17 +00002644 return StmtError(Diag(Literal->getLocStart(),
Daniel Dunbar58bc48c2009-08-19 20:04:03 +00002645 diag::err_asm_unknown_register_name) << Clobber);
Anders Carlsson290aa852007-11-25 00:25:21 +00002646 }
Sebastian Redl24b8e152009-01-18 16:53:17 +00002647
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002648 AsmStmt *NS =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2650 NumOutputs, NumInputs, Names, Constraints, Exprs,
Anders Carlsson98323d22010-01-30 23:19:41 +00002651 AsmString, NumClobbers, Clobbers, RParenLoc);
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002652 // Validate the asm string, ensuring it makes sense given the operands we
2653 // have.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002654 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002655 unsigned DiagOffs;
2656 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Chris Lattner0cdaa2e2009-03-10 23:57:07 +00002657 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2658 << AsmString->getSourceRange();
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002659 return StmtError();
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
Chris Lattner34b51e82009-05-03 05:55:43 +00002662 // Validate tied input operands for type mismatches.
2663 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2664 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
Mike Stump11289f42009-09-09 15:08:12 +00002665
Chris Lattner34b51e82009-05-03 05:55:43 +00002666 // If this is a tied constraint, verify that the output and input have
2667 // either exactly the same type, or that they are int/ptr operands with the
2668 // same size (int/long, int*/long, are ok etc).
2669 if (!Info.hasTiedOperand()) continue;
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattner34b51e82009-05-03 05:55:43 +00002671 unsigned TiedTo = Info.getTiedOperand();
Chris Lattner93ede022011-02-21 22:09:29 +00002672 unsigned InputOpNo = i+NumOutputs;
Chris Lattnercb66c732009-05-03 07:04:21 +00002673 Expr *OutputExpr = Exprs[TiedTo];
Chris Lattner93ede022011-02-21 22:09:29 +00002674 Expr *InputExpr = Exprs[InputOpNo];
Eli Friedman8eac6c22011-09-14 19:20:00 +00002675
2676 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2677 continue;
2678
Chris Lattner2c295cf2009-05-03 05:59:17 +00002679 QualType InTy = InputExpr->getType();
2680 QualType OutTy = OutputExpr->getType();
2681 if (Context.hasSameType(InTy, OutTy))
Chris Lattner34b51e82009-05-03 05:55:43 +00002682 continue; // All types can be tied to themselves.
Mike Stump11289f42009-09-09 15:08:12 +00002683
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002684 // Decide if the input and output are in the same domain (integer/ptr or
2685 // floating point.
2686 enum AsmDomain {
2687 AD_Int, AD_FP, AD_Other
2688 } InputDomain, OutputDomain;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002689
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002690 if (InTy->isIntegerType() || InTy->isPointerType())
2691 InputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002692 else if (InTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002693 InputDomain = AD_FP;
2694 else
2695 InputDomain = AD_Other;
Mike Stump11289f42009-09-09 15:08:12 +00002696
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002697 if (OutTy->isIntegerType() || OutTy->isPointerType())
2698 OutputDomain = AD_Int;
Douglas Gregor49b4d732010-06-22 23:07:26 +00002699 else if (OutTy->isRealFloatingType())
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002700 OutputDomain = AD_FP;
2701 else
2702 OutputDomain = AD_Other;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002704 // They are ok if they are the same size and in the same domain. This
2705 // allows tying things like:
2706 // void* to int*
2707 // void* to int if they are the same size.
2708 // double to long double if they are the same size.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709 //
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002710 uint64_t OutSize = Context.getTypeSize(OutTy);
2711 uint64_t InSize = Context.getTypeSize(InTy);
2712 if (OutSize == InSize && InputDomain == OutputDomain &&
2713 InputDomain != AD_Other)
2714 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002716 // If the smaller input/output operand is not mentioned in the asm string,
Chris Lattnere3694b12011-02-21 21:50:25 +00002717 // then we can promote the smaller one to a larger input and the asm string
2718 // won't notice.
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002719 bool SmallerValueMentioned = false;
Chad Rosiercc6a9082012-06-20 18:51:04 +00002720
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002721 // If this is a reference to the input and if the input was the smaller
2722 // one, then we have to reject this asm.
Chris Lattner93ede022011-02-21 22:09:29 +00002723 if (isOperandMentioned(InputOpNo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002724 // This is a use in the asm string of the smaller operand. Since we
2725 // codegen this by promoting to a wider value, the asm will get printed
2726 // "wrong".
Chris Lattnere3694b12011-02-21 21:50:25 +00002727 SmallerValueMentioned |= InSize < OutSize;
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002728 }
Chris Lattnere3694b12011-02-21 21:50:25 +00002729 if (isOperandMentioned(TiedTo, Pieces)) {
Chris Lattner70a4e9b2011-02-21 21:40:33 +00002730 // If this is a reference to the output, and if the output is the larger
2731 // value, then it's ok because we'll promote the input to the larger type.
Chris Lattnere3694b12011-02-21 21:50:25 +00002732 SmallerValueMentioned |= OutSize < InSize;
Chris Lattner34b51e82009-05-03 05:55:43 +00002733 }
Mike Stump11289f42009-09-09 15:08:12 +00002734
Chris Lattnerdb6d5cb2010-04-23 17:27:29 +00002735 // If the smaller value wasn't mentioned in the asm string, and if the
2736 // output was a register, just extend the shorter one to the size of the
2737 // larger one.
2738 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2739 OutputConstraintInfos[TiedTo].allowsRegister())
2740 continue;
Chad Rosiercc6a9082012-06-20 18:51:04 +00002741
Chris Lattner93ede022011-02-21 22:09:29 +00002742 // Either both of the operands were mentioned or the smaller one was
2743 // mentioned. One more special case that we'll allow: if the tied input is
2744 // integer, unmentioned, and is a constant, then we'll allow truncating it
2745 // down to the size of the destination.
2746 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2747 !isOperandMentioned(InputOpNo, Pieces) &&
2748 InputExpr->isEvaluatable(Context)) {
John McCalldfbf9342011-05-10 23:39:47 +00002749 CastKind castKind =
2750 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2751 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
Chris Lattner93ede022011-02-21 22:09:29 +00002752 Exprs[InputOpNo] = InputExpr;
2753 NS->setInputExpr(i, InputExpr);
2754 continue;
2755 }
Chad Rosiercc6a9082012-06-20 18:51:04 +00002756
Chris Lattner28b05c82009-05-03 06:50:40 +00002757 Diag(InputExpr->getLocStart(),
Chris Lattner34b51e82009-05-03 05:55:43 +00002758 diag::err_asm_tying_incompatible_types)
Chris Lattner2c295cf2009-05-03 05:59:17 +00002759 << InTy << OutTy << OutputExpr->getSourceRange()
Chris Lattner34b51e82009-05-03 05:55:43 +00002760 << InputExpr->getSourceRange();
Chris Lattner34b51e82009-05-03 05:55:43 +00002761 return StmtError();
2762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
Chris Lattnerd8c7ba22009-03-10 23:41:04 +00002764 return Owned(NS);
Chris Lattner73c56c02007-10-29 04:04:16 +00002765}
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00002766
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002767static void patchMSAsmStrings(Sema &SemaRef, bool &IsSimple,
2768 SourceLocation AsmLoc,
2769 ArrayRef<Token> AsmToks,
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002770 const TargetInfo &TI,
Chad Rosier592b90a2012-08-16 17:10:59 +00002771 std::vector<llvm::BitVector> &AsmRegs,
2772 std::vector<llvm::BitVector> &AsmNames,
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002773 std::vector<std::string> &AsmStrings) {
Chad Rosier3674eba2012-08-10 18:20:12 +00002774 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosierd12b7a62012-08-08 18:22:06 +00002775
Chad Rosier3674eba2012-08-10 18:20:12 +00002776 // Assume simple asm stmt until we parse a non-register identifer.
2777 IsSimple = true;
2778
Chad Rosier25e8fe62012-08-14 20:58:21 +00002779 SmallString<512> Asm;
2780 unsigned NumAsmStrings = 0;
2781 for (unsigned i = 0, e = AsmToks.size(); i != e; ++i) {
Chad Rosierd12b7a62012-08-08 18:22:06 +00002782
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002783 // Determine if this should be considered a new asm.
2784 bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2785 AsmToks[i].is(tok::kw_asm);
2786
Chad Rosier25e8fe62012-08-14 20:58:21 +00002787 // Emit the previous asm string.
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002788 if (i && isNewAsm) {
Chad Rosierecf77b52012-08-15 19:12:42 +00002789 AsmStrings[NumAsmStrings++] = Asm.c_str();
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002790 if (AsmToks[i].is(tok::kw_asm)) {
2791 ++i; // Skip __asm
2792 assert (i != e && "Expected another token.");
2793 }
2794 }
Chad Rosiera6e89aa2012-08-14 22:11:17 +00002795
Chad Rosier25e8fe62012-08-14 20:58:21 +00002796 // Start a new asm string with the opcode.
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002797 if (isNewAsm) {
Chad Rosier592b90a2012-08-16 17:10:59 +00002798 AsmRegs[NumAsmStrings].resize(AsmToks.size());
2799 AsmNames[NumAsmStrings].resize(AsmToks.size());
Chad Rosier25e8fe62012-08-14 20:58:21 +00002800 Asm = AsmToks[i].getIdentifierInfo()->getName().str();
2801 continue;
Chad Rosierd12b7a62012-08-08 18:22:06 +00002802 }
Chad Rosier25e8fe62012-08-14 20:58:21 +00002803
Chad Rosiera6e89aa2012-08-14 22:11:17 +00002804 if (i && AsmToks[i].hasLeadingSpace())
2805 Asm += ' ';
Chad Rosier25e8fe62012-08-14 20:58:21 +00002806
2807 // Check the operand(s).
2808 switch (AsmToks[i].getKind()) {
2809 default:
2810 //llvm_unreachable("Unknown token.");
2811 break;
2812 case tok::comma: Asm += ","; break;
2813 case tok::colon: Asm += ":"; break;
2814 case tok::l_square: Asm += "["; break;
2815 case tok::r_square: Asm += "]"; break;
2816 case tok::l_brace: Asm += "{"; break;
2817 case tok::r_brace: Asm += "}"; break;
2818 case tok::numeric_constant: {
2819 SmallString<32> TokenBuf;
2820 TokenBuf.resize(32);
2821 bool StringInvalid = false;
2822 Asm += SemaRef.PP.getSpelling(AsmToks[i], TokenBuf, &StringInvalid);
2823 assert (!StringInvalid && "Expected valid string!");
2824 break;
2825 }
2826 case tok::identifier: {
2827 StringRef Name = AsmToks[i].getIdentifierInfo()->getName();
2828
Chad Rosier592b90a2012-08-16 17:10:59 +00002829 // Valid register?
Chad Rosier25e8fe62012-08-14 20:58:21 +00002830 if (TI.isValidGCCRegisterName(Name)) {
Chad Rosier592b90a2012-08-16 17:10:59 +00002831 AsmRegs[NumAsmStrings].set(i);
Chad Rosier25e8fe62012-08-14 20:58:21 +00002832 Asm += Name;
2833 break;
2834 }
2835
Chad Rosier25e8fe62012-08-14 20:58:21 +00002836 IsSimple = false;
Chad Rosier592b90a2012-08-16 17:10:59 +00002837
2838 // FIXME: Why are we missing this segment register?
2839 if (Name == "fs") {
2840 Asm += Name;
2841 break;
2842 }
2843
2844 // Not a register, so this must be a variable, function or label
2845 // reference. Track these as they are either an Input or an Output.
2846 // Unfortunately, we don't know which is which until after we feed
2847 // the patched asms to the AsmParser.
2848 AsmNames[NumAsmStrings].set(i);
2849
2850 // TODO: Lookup the identifier and patch appropriately.
Chad Rosier25e8fe62012-08-14 20:58:21 +00002851 break;
2852 }
2853 } // AsmToks[i].getKind()
Chad Rosierd12b7a62012-08-08 18:22:06 +00002854 }
Chad Rosier25e8fe62012-08-14 20:58:21 +00002855
2856 // Emit the final (and possibly only) asm string.
2857 AsmStrings[NumAsmStrings] = Asm.c_str();
Chad Rosierd12b7a62012-08-08 18:22:06 +00002858}
2859
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002860// Build the unmodified MSAsmString.
2861static std::string buildMSAsmString(Sema &SemaRef,
Chad Rosier712faa22012-08-15 21:08:52 +00002862 ArrayRef<Token> AsmToks,
2863 unsigned &NumAsmStrings) {
Chad Rosier3674eba2012-08-10 18:20:12 +00002864 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002865 SmallString<512> Asm;
2866 SmallString<512> TokenBuf;
2867 TokenBuf.resize(512);
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002868
Chad Rosier712faa22012-08-15 21:08:52 +00002869 NumAsmStrings = 0;
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002870 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002871 bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2872 AsmToks[i].is(tok::kw_asm);
2873
2874 if (isNewAsm) {
Chad Rosier712faa22012-08-15 21:08:52 +00002875 ++NumAsmStrings;
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002876 if (i)
2877 Asm += '\n';
2878 if (AsmToks[i].is(tok::kw_asm)) {
2879 i++; // Skip __asm
2880 assert (i != e && "Expected another token");
2881 }
2882 }
2883
2884 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002885 Asm += ' ';
Chad Rosieraa7c1cb2012-08-15 21:03:27 +00002886
2887 bool StringInvalid = false;
Chad Rosierbba12af2012-08-14 21:48:01 +00002888 Asm += SemaRef.PP.getSpelling(AsmToks[i], TokenBuf, &StringInvalid);
2889 assert (!StringInvalid && "Expected valid string!");
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002890 }
2891 return Asm.c_str();
2892}
2893
Chad Rosier32503022012-06-11 20:47:18 +00002894StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
Chad Rosierb6f46c12012-08-15 16:53:30 +00002895 SourceLocation LBraceLoc,
Chad Rosier99fc3812012-08-07 00:29:06 +00002896 ArrayRef<Token> AsmToks,
Chad Rosier32503022012-06-11 20:47:18 +00002897 SourceLocation EndLoc) {
Chad Rosier43b7c022012-06-20 18:28:37 +00002898 // MS-style inline assembly is not fully supported, so emit a warning.
2899 Diag(AsmLoc, diag::warn_unsupported_msasm);
Chad Rosierd6ef7042012-08-10 21:06:19 +00002900 SmallVector<StringRef,4> Clobbers;
Chad Rosierb32f3d52012-08-15 21:55:19 +00002901 std::set<std::string> ClobberRegs;
Chad Rosier7dbef3e2012-08-16 00:06:53 +00002902 SmallVector<IdentifierInfo*, 4> Inputs;
2903 SmallVector<IdentifierInfo*, 4> Outputs;
Chad Rosier43b7c022012-06-20 18:28:37 +00002904
Chad Rosier543cb3e2012-08-09 20:52:43 +00002905 // Empty asm statements don't need to instantiate the AsmParser, etc.
2906 if (AsmToks.empty()) {
Chad Rosier8640a2a2012-08-09 21:06:32 +00002907 StringRef AsmString;
Chad Rosier543cb3e2012-08-09 20:52:43 +00002908 MSAsmStmt *NS =
Chad Rosier7dbef3e2012-08-16 00:06:53 +00002909 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2910 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2911 AsmString, Clobbers, EndLoc);
Chad Rosier543cb3e2012-08-09 20:52:43 +00002912 return Owned(NS);
2913 }
2914
Chad Rosier712faa22012-08-15 21:08:52 +00002915 unsigned NumAsmStrings;
2916 std::string AsmString = buildMSAsmString(*this, AsmToks, NumAsmStrings);
Chad Rosier3ed0bd92012-08-08 19:48:07 +00002917
Chad Rosierd12b7a62012-08-08 18:22:06 +00002918 bool IsSimple;
Chad Rosier592b90a2012-08-16 17:10:59 +00002919 std::vector<llvm::BitVector> Regs;
2920 std::vector<llvm::BitVector> Names;
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002921 std::vector<std::string> PatchedAsmStrings;
Chad Rosier592b90a2012-08-16 17:10:59 +00002922
2923 Regs.resize(NumAsmStrings);
2924 Names.resize(NumAsmStrings);
Chad Rosier712faa22012-08-15 21:08:52 +00002925 PatchedAsmStrings.resize(NumAsmStrings);
Chad Rosierd12b7a62012-08-08 18:22:06 +00002926
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002927 // Rewrite operands to appease the AsmParser.
Chad Rosier592b90a2012-08-16 17:10:59 +00002928 patchMSAsmStrings(*this, IsSimple, AsmLoc, AsmToks,
2929 Context.getTargetInfo(), Regs, Names, PatchedAsmStrings);
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002930
2931 // patchMSAsmStrings doesn't correctly patch non-simple asm statements.
Chad Rosierf32302a2012-08-10 21:27:11 +00002932 if (!IsSimple) {
2933 MSAsmStmt *NS =
Chad Rosier7dbef3e2012-08-16 00:06:53 +00002934 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2935 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2936 AsmString, Clobbers, EndLoc);
Chad Rosierf32302a2012-08-10 21:27:11 +00002937 return Owned(NS);
2938 }
2939
Chad Rosierd5c43a52012-08-09 17:33:11 +00002940 // Initialize targets and assembly printers/parsers.
2941 llvm::InitializeAllTargetInfos();
2942 llvm::InitializeAllTargetMCs();
2943 llvm::InitializeAllAsmParsers();
2944
Chad Rosier11ede932012-08-09 20:47:38 +00002945 // Get the target specific parser.
2946 std::string Error;
2947 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
2948 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
2949
Chad Rosier11ede932012-08-09 20:47:38 +00002950 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
2951 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2952 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
Chad Rosier11ede932012-08-09 20:47:38 +00002953 OwningPtr<llvm::MCSubtargetInfo>
2954 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2955
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002956 for (unsigned i = 0, e = PatchedAsmStrings.size(); i != e; ++i) {
2957 llvm::SourceMgr SrcMgr;
2958 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
2959 llvm::MemoryBuffer *Buffer =
2960 llvm::MemoryBuffer::getMemBuffer(PatchedAsmStrings[i], "<inline asm>");
Chad Rosier11ede932012-08-09 20:47:38 +00002961
Chad Rosier65a8e0b2012-08-13 20:32:07 +00002962 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2963 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2964
2965 OwningPtr<llvm::MCStreamer> Str;
2966 OwningPtr<llvm::MCAsmParser>
2967 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
2968 OwningPtr<llvm::MCTargetAsmParser>
2969 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
2970 // Change to the Intel dialect.
2971 Parser->setAssemblerDialect(1);
2972 Parser->setTargetParser(*TargetParser.get());
2973
Chad Rosier222ed4b2012-08-15 00:42:47 +00002974 // Prime the lexer.
2975 Parser->Lex();
2976
2977 // Parse the opcode.
2978 StringRef IDVal;
2979 Parser->ParseIdentifier(IDVal);
2980
2981 // Canonicalize the opcode to lower case.
2982 SmallString<128> Opcode;
2983 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
2984 Opcode.push_back(tolower(IDVal[i]));
2985
2986 // Parse the operands.
2987 llvm::SMLoc IDLoc;
2988 SmallVector<llvm::MCParsedAsmOperand*, 8> Operands;
2989 bool HadError = TargetParser->ParseInstruction(Opcode.str(), IDLoc,
2990 Operands);
2991 assert (!HadError && "Unexpected error parsing instruction");
2992
2993 // Match the MCInstr.
2994 SmallVector<llvm::MCInst, 2> Instrs;
2995 HadError = TargetParser->MatchInstruction(IDLoc, Operands, Instrs);
2996 assert (!HadError && "Unexpected error matching instruction");
2997 assert ((Instrs.size() == 1) && "Expected only a single instruction.");
2998
2999 // Get the instruction descriptor.
3000 llvm::MCInst Inst = Instrs[0];
3001 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
3002 const llvm::MCInstrDesc &Desc = MII->get(Inst.getOpcode());
3003 llvm::MCInstPrinter *IP =
3004 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
3005
3006 // Build the list of clobbers.
3007 for (unsigned i = 0, e = Desc.getNumDefs(); i != e; ++i) {
3008 const llvm::MCOperand &Op = Inst.getOperand(i);
3009 if (!Op.isReg())
3010 continue;
3011
Chad Rosierb32f3d52012-08-15 21:55:19 +00003012 std::string Reg;
3013 llvm::raw_string_ostream OS(Reg);
Chad Rosier222ed4b2012-08-15 00:42:47 +00003014 IP->printRegName(OS, Op.getReg());
3015
3016 StringRef Clobber(OS.str());
3017 if (!Context.getTargetInfo().isValidClobber(Clobber))
3018 return StmtError(Diag(AsmLoc, diag::err_asm_unknown_register_name) <<
3019 Clobber);
Chad Rosierb32f3d52012-08-15 21:55:19 +00003020 ClobberRegs.insert(Reg);
Chad Rosier222ed4b2012-08-15 00:42:47 +00003021 }
Chad Rosier65a8e0b2012-08-13 20:32:07 +00003022 }
Chad Rosierb32f3d52012-08-15 21:55:19 +00003023 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3024 E = ClobberRegs.end(); I != E; ++I)
3025 Clobbers.push_back(*I);
Chad Rosier11ede932012-08-09 20:47:38 +00003026
Chad Rosier32503022012-06-11 20:47:18 +00003027 MSAsmStmt *NS =
Chad Rosier7dbef3e2012-08-16 00:06:53 +00003028 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
3029 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
3030 AsmString, Clobbers, EndLoc);
Chad Rosier32503022012-06-11 20:47:18 +00003031 return Owned(NS);
3032}
3033
John McCalldadc5752010-08-24 06:29:42 +00003034StmtResult
Sebastian Redl481bf3f2009-01-18 17:43:11 +00003035Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
John McCall48871652010-08-21 09:40:31 +00003036 SourceLocation RParen, Decl *Parm,
John McCallb268a282010-08-23 23:25:46 +00003037 Stmt *Body) {
John McCall48871652010-08-21 09:40:31 +00003038 VarDecl *Var = cast_or_null<VarDecl>(Parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003039 if (Var && Var->isInvalidDecl())
3040 return StmtError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003041
John McCallb268a282010-08-23 23:25:46 +00003042 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
Fariborz Jahanian9e63b982007-11-01 23:59:59 +00003043}
3044
John McCalldadc5752010-08-24 06:29:42 +00003045StmtResult
John McCallb268a282010-08-23 23:25:46 +00003046Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3047 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
Fariborz Jahanian71234d82007-11-02 00:18:53 +00003048}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003049
John McCalldadc5752010-08-24 06:29:42 +00003050StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
John McCallb268a282010-08-23 23:25:46 +00003052 MultiStmtArg CatchStmts, Stmt *Finally) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003053 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003054 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3055
John McCallaab3e412010-08-25 08:40:02 +00003056 getCurFunction()->setHasBranchProtectedScope();
Douglas Gregor96c79492010-04-23 22:50:49 +00003057 unsigned NumCatchStmts = CatchStmts.size();
John McCallb268a282010-08-23 23:25:46 +00003058 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
3059 CatchStmts.release(),
Douglas Gregor96c79492010-04-23 22:50:49 +00003060 NumCatchStmts,
John McCallb268a282010-08-23 23:25:46 +00003061 Finally));
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003062}
3063
John McCall0bd3e402012-05-08 21:41:25 +00003064StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
Douglas Gregor2900c162010-04-22 21:44:01 +00003065 if (Throw) {
John Wiegley01296292011-04-08 18:41:53 +00003066 ExprResult Result = DefaultLvalueConversion(Throw);
3067 if (Result.isInvalid())
3068 return StmtError();
John McCall15317a22010-12-15 04:42:30 +00003069
John McCall0bd3e402012-05-08 21:41:25 +00003070 Throw = MaybeCreateExprWithCleanups(Result.take());
Douglas Gregor2900c162010-04-22 21:44:01 +00003071 QualType ThrowType = Throw->getType();
3072 // Make sure the expression type is an ObjC pointer or "void *".
3073 if (!ThrowType->isDependentType() &&
3074 !ThrowType->isObjCObjectPointerType()) {
3075 const PointerType *PT = ThrowType->getAs<PointerType>();
3076 if (!PT || !PT->getPointeeType()->isVoidType())
3077 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3078 << Throw->getType() << Throw->getSourceRange());
3079 }
3080 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081
John McCallb268a282010-08-23 23:25:46 +00003082 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
Douglas Gregor2900c162010-04-22 21:44:01 +00003083}
3084
John McCalldadc5752010-08-24 06:29:42 +00003085StmtResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Douglas Gregor2900c162010-04-22 21:44:01 +00003087 Scope *CurScope) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003088 if (!getLangOpts().ObjCExceptions)
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003089 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3090
John McCallb268a282010-08-23 23:25:46 +00003091 if (!Throw) {
Steve Naroff5ee2c022009-02-11 20:05:44 +00003092 // @throw without an expression designates a rethrow (which much occur
3093 // in the context of an @catch clause).
3094 Scope *AtCatchParent = CurScope;
3095 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3096 AtCatchParent = AtCatchParent->getParent();
3097 if (!AtCatchParent)
Steve Naroffc49b22a2009-02-12 18:09:32 +00003098 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003099 }
John McCallb268a282010-08-23 23:25:46 +00003100 return BuildObjCAtThrowStmt(AtLoc, Throw);
Fariborz Jahanianadfbbc32007-11-07 02:00:49 +00003101}
Fariborz Jahanianf859ef22007-11-02 15:39:31 +00003102
John McCalld9bb7432011-07-27 21:50:02 +00003103ExprResult
3104Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3105 ExprResult result = DefaultLvalueConversion(operand);
3106 if (result.isInvalid())
3107 return ExprError();
3108 operand = result.take();
3109
3110 // Make sure the expression type is an ObjC pointer or "void *".
3111 QualType type = operand->getType();
3112 if (!type->isDependentType() &&
3113 !type->isObjCObjectPointerType()) {
3114 const PointerType *pointerType = type->getAs<PointerType>();
3115 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3116 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3117 << type << operand->getSourceRange();
3118 }
3119
3120 // The operand to @synchronized is a full-expression.
3121 return MaybeCreateExprWithCleanups(operand);
3122}
3123
John McCalldadc5752010-08-24 06:29:42 +00003124StmtResult
John McCallb268a282010-08-23 23:25:46 +00003125Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3126 Stmt *SyncBody) {
John McCalld9bb7432011-07-27 21:50:02 +00003127 // We can't jump into or indirect-jump out of a @synchronized block.
John McCallaab3e412010-08-25 08:40:02 +00003128 getCurFunction()->setHasBranchProtectedScope();
John McCallb268a282010-08-23 23:25:46 +00003129 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
Fariborz Jahanian48085b82008-01-29 19:14:59 +00003130}
Sebastian Redl54c04d42008-12-22 19:15:10 +00003131
3132/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3133/// and creates a proper catch handler from them.
John McCalldadc5752010-08-24 06:29:42 +00003134StmtResult
John McCall48871652010-08-21 09:40:31 +00003135Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
John McCallb268a282010-08-23 23:25:46 +00003136 Stmt *HandlerBlock) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00003137 // There's nothing to test that ActOnExceptionDecl didn't already test.
Ted Kremenek5a201952009-02-07 01:47:29 +00003138 return Owned(new (Context) CXXCatchStmt(CatchLoc,
John McCall48871652010-08-21 09:40:31 +00003139 cast_or_null<VarDecl>(ExDecl),
John McCallb268a282010-08-23 23:25:46 +00003140 HandlerBlock));
Sebastian Redl54c04d42008-12-22 19:15:10 +00003141}
Sebastian Redl9b244a82008-12-22 21:35:02 +00003142
John McCall31168b02011-06-15 23:02:42 +00003143StmtResult
3144Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3145 getCurFunction()->setHasBranchProtectedScope();
3146 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3147}
3148
Dan Gohman28ade552010-07-26 21:25:24 +00003149namespace {
3150
Sebastian Redl63c4da02009-07-29 17:15:45 +00003151class TypeWithHandler {
3152 QualType t;
3153 CXXCatchStmt *stmt;
3154public:
3155 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3156 : t(type), stmt(statement) {}
3157
John McCall8ccfcb52009-09-24 19:53:00 +00003158 // An arbitrary order is fine as long as it places identical
3159 // types next to each other.
Sebastian Redl63c4da02009-07-29 17:15:45 +00003160 bool operator<(const TypeWithHandler &y) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003161 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003162 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003163 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
Sebastian Redl63c4da02009-07-29 17:15:45 +00003164 return false;
3165 else
3166 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
Sebastian Redl63c4da02009-07-29 17:15:45 +00003169 bool operator==(const TypeWithHandler& other) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003170 return t == other.t;
Sebastian Redl63c4da02009-07-29 17:15:45 +00003171 }
Mike Stump11289f42009-09-09 15:08:12 +00003172
Sebastian Redl63c4da02009-07-29 17:15:45 +00003173 CXXCatchStmt *getCatchStmt() const { return stmt; }
3174 SourceLocation getTypeSpecStartLoc() const {
3175 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3176 }
3177};
3178
Dan Gohman28ade552010-07-26 21:25:24 +00003179}
3180
Sebastian Redl9b244a82008-12-22 21:35:02 +00003181/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3182/// handlers and creates a try statement from them.
John McCalldadc5752010-08-24 06:29:42 +00003183StmtResult
John McCallb268a282010-08-23 23:25:46 +00003184Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
Sebastian Redl9b244a82008-12-22 21:35:02 +00003185 MultiStmtArg RawHandlers) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003186 // Don't report an error if 'try' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003187 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +00003188 !getSourceManager().isInSystemHeader(TryLoc))
3189 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
Anders Carlsson68b36af2011-02-19 19:26:44 +00003190
Sebastian Redl9b244a82008-12-22 21:35:02 +00003191 unsigned NumHandlers = RawHandlers.size();
3192 assert(NumHandlers > 0 &&
3193 "The parser shouldn't call this if there are no handlers.");
John McCallb268a282010-08-23 23:25:46 +00003194 Stmt **Handlers = RawHandlers.get();
Sebastian Redl9b244a82008-12-22 21:35:02 +00003195
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003196 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
Mike Stump11289f42009-09-09 15:08:12 +00003197
3198 for (unsigned i = 0; i < NumHandlers; ++i) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003199 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
Sebastian Redl63c4da02009-07-29 17:15:45 +00003200 if (!Handler->getExceptionDecl()) {
3201 if (i < NumHandlers - 1)
3202 return StmtError(Diag(Handler->getLocStart(),
3203 diag::err_early_catch_all));
Mike Stump11289f42009-09-09 15:08:12 +00003204
Sebastian Redl63c4da02009-07-29 17:15:45 +00003205 continue;
3206 }
Mike Stump11289f42009-09-09 15:08:12 +00003207
Sebastian Redl63c4da02009-07-29 17:15:45 +00003208 const QualType CaughtType = Handler->getCaughtType();
3209 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3210 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003211 }
Sebastian Redl63c4da02009-07-29 17:15:45 +00003212
3213 // Detect handlers for the same type as an earlier one.
3214 if (NumHandlers > 1) {
3215 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
Mike Stump11289f42009-09-09 15:08:12 +00003216
Sebastian Redl63c4da02009-07-29 17:15:45 +00003217 TypeWithHandler prev = TypesWithHandlers[0];
3218 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3219 TypeWithHandler curr = TypesWithHandlers[i];
Mike Stump11289f42009-09-09 15:08:12 +00003220
Sebastian Redl63c4da02009-07-29 17:15:45 +00003221 if (curr == prev) {
3222 Diag(curr.getTypeSpecStartLoc(),
3223 diag::warn_exception_caught_by_earlier_handler)
3224 << curr.getCatchStmt()->getCaughtType().getAsString();
3225 Diag(prev.getTypeSpecStartLoc(),
3226 diag::note_previous_exception_handler)
3227 << prev.getCatchStmt()->getCaughtType().getAsString();
3228 }
Mike Stump11289f42009-09-09 15:08:12 +00003229
Sebastian Redl63c4da02009-07-29 17:15:45 +00003230 prev = curr;
3231 }
3232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233
John McCallaab3e412010-08-25 08:40:02 +00003234 getCurFunction()->setHasBranchProtectedScope();
John McCalla95172b2010-08-01 00:26:45 +00003235
Sebastian Redl9b244a82008-12-22 21:35:02 +00003236 // FIXME: We should detect handlers that cannot catch anything because an
3237 // earlier handler catches a superclass. Need to find a method that is not
3238 // quadratic for this.
3239 // Neither of these are explicitly forbidden, but every compiler detects them
3240 // and warns.
3241
John McCallb268a282010-08-23 23:25:46 +00003242 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
Sam Weiniga16b0dd2010-02-03 03:56:39 +00003243 Handlers, NumHandlers));
Sebastian Redl9b244a82008-12-22 21:35:02 +00003244}
John Wiegley1c0675e2011-04-28 01:08:34 +00003245
3246StmtResult
3247Sema::ActOnSEHTryBlock(bool IsCXXTry,
3248 SourceLocation TryLoc,
3249 Stmt *TryBlock,
3250 Stmt *Handler) {
3251 assert(TryBlock && Handler);
3252
3253 getCurFunction()->setHasBranchProtectedScope();
3254
3255 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3256}
3257
3258StmtResult
3259Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3260 Expr *FilterExpr,
3261 Stmt *Block) {
3262 assert(FilterExpr && Block);
3263
3264 if(!FilterExpr->getType()->isIntegerType()) {
Francois Pichetfbf7e172011-06-02 00:47:27 +00003265 return StmtError(Diag(FilterExpr->getExprLoc(),
3266 diag::err_filter_expression_integral)
3267 << FilterExpr->getType());
John Wiegley1c0675e2011-04-28 01:08:34 +00003268 }
3269
3270 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3271}
3272
3273StmtResult
3274Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3275 Stmt *Block) {
3276 assert(Block);
3277 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3278}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003279
3280StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3281 bool IsIfExists,
3282 NestedNameSpecifierLoc QualifierLoc,
3283 DeclarationNameInfo NameInfo,
3284 Stmt *Nested)
3285{
3286 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003287 QualifierLoc, NameInfo,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003288 cast<CompoundStmt>(Nested));
3289}
3290
3291
Chad Rosier02a84392012-08-10 17:56:09 +00003292StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003293 bool IsIfExists,
Chad Rosier02a84392012-08-10 17:56:09 +00003294 CXXScopeSpec &SS,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003295 UnqualifiedId &Name,
3296 Stmt *Nested) {
Chad Rosier02a84392012-08-10 17:56:09 +00003297 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00003298 SS.getWithLocInContext(Context),
3299 GetNameFromUnqualifiedId(Name),
3300 Nested);
3301}