blob: 0dbe8ced1877d20d26a70cac80b9131d7a75ea82 [file] [log] [blame]
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ lambda expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/DeclSpec.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000014#include "TypeLocBuilder.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000015#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ExprCXX.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000017#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
Douglas Gregor6f88e5e2012-02-21 04:17:39 +000021#include "clang/Sema/Scope.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000022#include "clang/Sema/ScopeInfo.h"
23#include "clang/Sema/SemaInternal.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/Sema/SemaLambda.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000025using namespace clang;
26using namespace sema;
27
Faisal Valiab3d6462013-12-07 20:22:44 +000028/// \brief Examines the FunctionScopeInfo stack to determine the nearest
29/// enclosing lambda (to the current lambda) that is 'capture-ready' for
30/// the variable referenced in the current lambda (i.e. \p VarToCapture).
31/// If successful, returns the index into Sema's FunctionScopeInfo stack
32/// of the capture-ready lambda's LambdaScopeInfo.
33///
34/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
35/// lambda - is on top) to determine the index of the nearest enclosing/outer
36/// lambda that is ready to capture the \p VarToCapture being referenced in
37/// the current lambda.
38/// As we climb down the stack, we want the index of the first such lambda -
39/// that is the lambda with the highest index that is 'capture-ready'.
40///
41/// A lambda 'L' is capture-ready for 'V' (var or this) if:
42/// - its enclosing context is non-dependent
43/// - and if the chain of lambdas between L and the lambda in which
44/// V is potentially used (i.e. the lambda at the top of the scope info
45/// stack), can all capture or have already captured V.
46/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
47///
48/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
49/// for whether it is 'capture-capable' (see
50/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
51/// capture.
52///
53/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
54/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
55/// is at the top of the stack and has the highest index.
56/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
57///
58/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
59/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
60/// which is capture-ready. If the return value evaluates to 'false' then
61/// no lambda is capture-ready for \p VarToCapture.
62
63static inline Optional<unsigned>
64getStackIndexOfNearestEnclosingCaptureReadyLambda(
65 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
66 VarDecl *VarToCapture) {
67 // Label failure to capture.
68 const Optional<unsigned> NoLambdaIsCaptureReady;
69
70 assert(
71 isa<clang::sema::LambdaScopeInfo>(
72 FunctionScopes[FunctionScopes.size() - 1]) &&
73 "The function on the top of sema's function-info stack must be a lambda");
Faisal Valia17d19f2013-11-07 05:17:06 +000074
Faisal Valiab3d6462013-12-07 20:22:44 +000075 // If VarToCapture is null, we are attempting to capture 'this'.
76 const bool IsCapturingThis = !VarToCapture;
Faisal Valia17d19f2013-11-07 05:17:06 +000077 const bool IsCapturingVariable = !IsCapturingThis;
Faisal Valiab3d6462013-12-07 20:22:44 +000078
79 // Start with the current lambda at the top of the stack (highest index).
Faisal Valia17d19f2013-11-07 05:17:06 +000080 unsigned CurScopeIndex = FunctionScopes.size() - 1;
Faisal Valiab3d6462013-12-07 20:22:44 +000081 DeclContext *EnclosingDC =
82 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
83
84 do {
85 const clang::sema::LambdaScopeInfo *LSI =
86 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
87 // IF we have climbed down to an intervening enclosing lambda that contains
88 // the variable declaration - it obviously can/must not capture the
Faisal Valia17d19f2013-11-07 05:17:06 +000089 // variable.
Faisal Valiab3d6462013-12-07 20:22:44 +000090 // Since its enclosing DC is dependent, all the lambdas between it and the
91 // innermost nested lambda are dependent (otherwise we wouldn't have
92 // arrived here) - so we don't yet have a lambda that can capture the
93 // variable.
94 if (IsCapturingVariable &&
95 VarToCapture->getDeclContext()->Equals(EnclosingDC))
96 return NoLambdaIsCaptureReady;
97
98 // For an enclosing lambda to be capture ready for an entity, all
99 // intervening lambda's have to be able to capture that entity. If even
100 // one of the intervening lambda's is not capable of capturing the entity
101 // then no enclosing lambda can ever capture that entity.
102 // For e.g.
103 // const int x = 10;
104 // [=](auto a) { #1
105 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
106 // [=](auto c) { #3
107 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
108 // }; }; };
Faisal Valia17d19f2013-11-07 05:17:06 +0000109 // If they do not have a default implicit capture, check to see
110 // if the entity has already been explicitly captured.
Faisal Valiab3d6462013-12-07 20:22:44 +0000111 // If even a single dependent enclosing lambda lacks the capability
112 // to ever capture this variable, there is no further enclosing
Faisal Valia17d19f2013-11-07 05:17:06 +0000113 // non-dependent lambda that can capture this variable.
114 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000115 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
116 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000117 if (IsCapturingThis && !LSI->isCXXThisCaptured())
Faisal Valiab3d6462013-12-07 20:22:44 +0000118 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000119 }
120 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
Faisal Valiab3d6462013-12-07 20:22:44 +0000121
122 assert(CurScopeIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +0000123 --CurScopeIndex;
Faisal Valiab3d6462013-12-07 20:22:44 +0000124 } while (!EnclosingDC->isTranslationUnit() &&
125 EnclosingDC->isDependentContext() &&
126 isLambdaCallOperator(EnclosingDC));
Faisal Valia17d19f2013-11-07 05:17:06 +0000127
Faisal Valiab3d6462013-12-07 20:22:44 +0000128 assert(CurScopeIndex < (FunctionScopes.size() - 1));
129 // If the enclosingDC is not dependent, then the immediately nested lambda
130 // (one index above) is capture-ready.
131 if (!EnclosingDC->isDependentContext())
132 return CurScopeIndex + 1;
133 return NoLambdaIsCaptureReady;
134}
135
136/// \brief Examines the FunctionScopeInfo stack to determine the nearest
137/// enclosing lambda (to the current lambda) that is 'capture-capable' for
138/// the variable referenced in the current lambda (i.e. \p VarToCapture).
139/// If successful, returns the index into Sema's FunctionScopeInfo stack
140/// of the capture-capable lambda's LambdaScopeInfo.
141///
142/// Given the current stack of lambdas being processed by Sema and
143/// the variable of interest, to identify the nearest enclosing lambda (to the
144/// current lambda at the top of the stack) that can truly capture
145/// a variable, it has to have the following two properties:
146/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
147/// - climb down the stack (i.e. starting from the innermost and examining
148/// each outer lambda step by step) checking if each enclosing
149/// lambda can either implicitly or explicitly capture the variable.
150/// Record the first such lambda that is enclosed in a non-dependent
151/// context. If no such lambda currently exists return failure.
152/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
153/// capture the variable by checking all its enclosing lambdas:
154/// - check if all outer lambdas enclosing the 'capture-ready' lambda
155/// identified above in 'a' can also capture the variable (this is done
156/// via tryCaptureVariable for variables and CheckCXXThisCapture for
157/// 'this' by passing in the index of the Lambda identified in step 'a')
158///
159/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
160/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
161/// is at the top of the stack.
162///
163/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
164///
165///
166/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
167/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
168/// which is capture-capable. If the return value evaluates to 'false' then
169/// no lambda is capture-capable for \p VarToCapture.
170
171Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
172 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
173 VarDecl *VarToCapture, Sema &S) {
174
Faisal Vali5035a8c2013-12-09 00:15:23 +0000175 const Optional<unsigned> NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000176
177 const Optional<unsigned> OptionalStackIndex =
178 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
179 VarToCapture);
180 if (!OptionalStackIndex)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000181 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000182
183 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
Faisal Vali5ab61b02013-12-08 15:00:29 +0000184 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
185 S.getCurGenericLambda()) &&
186 "The capture ready lambda for a potential capture can only be the "
Faisal Vali40e84582013-12-08 15:04:03 +0000187 "current lambda if it is a generic lambda");
Faisal Valiab3d6462013-12-07 20:22:44 +0000188
189 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
190 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
191
192 // If VarToCapture is null, we are attempting to capture 'this'
193 const bool IsCapturingThis = !VarToCapture;
Faisal Valia17d19f2013-11-07 05:17:06 +0000194 const bool IsCapturingVariable = !IsCapturingThis;
195
196 if (IsCapturingVariable) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000197 // Check if the capture-ready lambda can truly capture the variable, by
198 // checking whether all enclosing lambdas of the capture-ready lambda allow
199 // the capture - i.e. make sure it is capture-capable.
Faisal Valia17d19f2013-11-07 05:17:06 +0000200 QualType CaptureType, DeclRefType;
Faisal Valiab3d6462013-12-07 20:22:44 +0000201 const bool CanCaptureVariable =
202 !S.tryCaptureVariable(VarToCapture,
203 /*ExprVarIsUsedInLoc*/ SourceLocation(),
204 clang::Sema::TryCapture_Implicit,
205 /*EllipsisLoc*/ SourceLocation(),
206 /*BuildAndDiagnose*/ false, CaptureType,
207 DeclRefType, &IndexOfCaptureReadyLambda);
208 if (!CanCaptureVariable)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000209 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000210 } else {
211 // Check if the capture-ready lambda can truly capture 'this' by checking
212 // whether all enclosing lambdas of the capture-ready lambda can capture
213 // 'this'.
214 const bool CanCaptureThis =
215 !S.CheckCXXThisCapture(
216 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
217 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
218 &IndexOfCaptureReadyLambda);
219 if (!CanCaptureThis)
Faisal Vali5035a8c2013-12-09 00:15:23 +0000220 return NoLambdaIsCaptureCapable;
Faisal Valiab3d6462013-12-07 20:22:44 +0000221 }
222 return IndexOfCaptureReadyLambda;
Faisal Valia17d19f2013-11-07 05:17:06 +0000223}
Faisal Valic1a6dc42013-10-23 16:10:50 +0000224
225static inline TemplateParameterList *
226getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
227 if (LSI->GLTemplateParameterList)
228 return LSI->GLTemplateParameterList;
229
230 if (LSI->AutoTemplateParams.size()) {
231 SourceRange IntroRange = LSI->IntroducerRange;
232 SourceLocation LAngleLoc = IntroRange.getBegin();
233 SourceLocation RAngleLoc = IntroRange.getEnd();
234 LSI->GLTemplateParameterList = TemplateParameterList::Create(
Faisal Valiab3d6462013-12-07 20:22:44 +0000235 SemaRef.Context,
236 /*Template kw loc*/ SourceLocation(), LAngleLoc,
237 (NamedDecl **)LSI->AutoTemplateParams.data(),
238 LSI->AutoTemplateParams.size(), RAngleLoc);
Faisal Valic1a6dc42013-10-23 16:10:50 +0000239 }
240 return LSI->GLTemplateParameterList;
241}
242
Douglas Gregor680e9e02012-02-21 19:11:17 +0000243CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedmand564afb2012-09-19 01:18:11 +0000244 TypeSourceInfo *Info,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000245 bool KnownDependent,
246 LambdaCaptureDefault CaptureDefault) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000247 DeclContext *DC = CurContext;
248 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
249 DC = DC->getParent();
Faisal Valic1a6dc42013-10-23 16:10:50 +0000250 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
251 *this);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000252 // Start constructing the lambda class.
Eli Friedmand564afb2012-09-19 01:18:11 +0000253 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregor680e9e02012-02-21 19:11:17 +0000254 IntroducerRange.getBegin(),
Faisal Valic1a6dc42013-10-23 16:10:50 +0000255 KnownDependent,
256 IsGenericLambda,
257 CaptureDefault);
Douglas Gregor43c3f282012-02-20 20:47:06 +0000258 DC->addDecl(Class);
Richard Smith3d584b02014-02-06 21:49:08 +0000259
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000260 return Class;
261}
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000262
Douglas Gregorb61e8092012-04-04 17:40:10 +0000263/// \brief Determine whether the given context is or is enclosed in an inline
264/// function.
265static bool isInInlineFunction(const DeclContext *DC) {
266 while (!DC->isFileContext()) {
267 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
268 if (FD->isInlined())
269 return true;
270
271 DC = DC->getLexicalParent();
272 }
273
274 return false;
275}
276
Eli Friedman7e346a82013-07-01 20:22:57 +0000277MangleNumberingContext *
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000278Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman7e346a82013-07-01 20:22:57 +0000279 Decl *&ManglingContextDecl) {
280 // Compute the context for allocating mangling numbers in the current
281 // expression, if the ABI requires them.
282 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
283
284 enum ContextKind {
285 Normal,
286 DefaultArgument,
287 DataMember,
288 StaticDataMember
289 } Kind = Normal;
290
291 // Default arguments of member function parameters that appear in a class
292 // definition, as well as the initializers of data members, receive special
293 // treatment. Identify them.
294 if (ManglingContextDecl) {
295 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
296 if (const DeclContext *LexicalDC
297 = Param->getDeclContext()->getLexicalParent())
298 if (LexicalDC->isRecord())
299 Kind = DefaultArgument;
300 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
301 if (Var->getDeclContext()->isRecord())
302 Kind = StaticDataMember;
303 } else if (isa<FieldDecl>(ManglingContextDecl)) {
304 Kind = DataMember;
305 }
306 }
307
308 // Itanium ABI [5.1.7]:
309 // In the following contexts [...] the one-definition rule requires closure
310 // types in different translation units to "correspond":
311 bool IsInNonspecializedTemplate =
312 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
313 switch (Kind) {
314 case Normal:
315 // -- the bodies of non-exported nonspecialized template functions
316 // -- the bodies of inline functions
317 if ((IsInNonspecializedTemplate &&
318 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
319 isInInlineFunction(CurContext)) {
320 ManglingContextDecl = 0;
321 return &Context.getManglingNumberContext(DC);
322 }
323
324 ManglingContextDecl = 0;
325 return 0;
326
327 case StaticDataMember:
328 // -- the initializers of nonspecialized static members of template classes
329 if (!IsInNonspecializedTemplate) {
330 ManglingContextDecl = 0;
331 return 0;
332 }
333 // Fall through to get the current context.
334
335 case DataMember:
336 // -- the in-class initializers of class members
337 case DefaultArgument:
338 // -- default arguments appearing in class definitions
Reid Klecknerd8110b62013-09-10 20:14:30 +0000339 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman7e346a82013-07-01 20:22:57 +0000340 }
Andy Gibbs456198d2013-07-02 16:01:56 +0000341
342 llvm_unreachable("unexpected context");
Eli Friedman7e346a82013-07-01 20:22:57 +0000343}
344
Reid Klecknerd8110b62013-09-10 20:14:30 +0000345MangleNumberingContext &
346Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
347 ASTContext &Ctx) {
348 assert(ManglingContextDecl && "Need to have a context declaration");
349 if (!MangleNumbering)
350 MangleNumbering = Ctx.createMangleNumberingContext();
351 return *MangleNumbering;
352}
353
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000354CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith4db51c22013-09-25 05:02:54 +0000355 SourceRange IntroducerRange,
356 TypeSourceInfo *MethodTypeInfo,
357 SourceLocation EndLoc,
358 ArrayRef<ParmVarDecl *> Params) {
359 QualType MethodType = MethodTypeInfo->getType();
Faisal Vali2b391ab2013-09-26 19:54:12 +0000360 TemplateParameterList *TemplateParams =
361 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
362 // If a lambda appears in a dependent context or is a generic lambda (has
363 // template parameters) and has an 'auto' return type, deduce it to a
364 // dependent type.
365 if (Class->isDependentContext() || TemplateParams) {
Richard Smith4db51c22013-09-25 05:02:54 +0000366 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000367 QualType Result = FPT->getReturnType();
Richard Smith4db51c22013-09-25 05:02:54 +0000368 if (Result->isUndeducedType()) {
369 Result = SubstAutoType(Result, Context.DependentTy);
Alp Toker9cacbab2014-01-20 20:26:09 +0000370 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
Richard Smith4db51c22013-09-25 05:02:54 +0000371 FPT->getExtProtoInfo());
372 }
373 }
374
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000375 // C++11 [expr.prim.lambda]p5:
376 // The closure type for a lambda-expression has a public inline function
377 // call operator (13.5.4) whose parameters and return type are described by
378 // the lambda-expression's parameter-declaration-clause and
379 // trailing-return-type respectively.
380 DeclarationName MethodName
381 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
382 DeclarationNameLoc MethodNameLoc;
383 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
384 = IntroducerRange.getBegin().getRawEncoding();
385 MethodNameLoc.CXXOperatorName.EndOpNameLoc
386 = IntroducerRange.getEnd().getRawEncoding();
387 CXXMethodDecl *Method
388 = CXXMethodDecl::Create(Context, Class, EndLoc,
389 DeclarationNameInfo(MethodName,
390 IntroducerRange.getBegin(),
391 MethodNameLoc),
Richard Smith4db51c22013-09-25 05:02:54 +0000392 MethodType, MethodTypeInfo,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000393 SC_None,
394 /*isInline=*/true,
395 /*isConstExpr=*/false,
396 EndLoc);
397 Method->setAccess(AS_public);
398
399 // Temporarily set the lexical declaration context to the current
400 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregor43c3f282012-02-20 20:47:06 +0000401 Method->setLexicalDeclContext(CurContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000402 // Create a function template if we have a template parameter list
403 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
404 FunctionTemplateDecl::Create(Context, Class,
405 Method->getLocation(), MethodName,
406 TemplateParams,
407 Method) : 0;
408 if (TemplateMethod) {
409 TemplateMethod->setLexicalDeclContext(CurContext);
410 TemplateMethod->setAccess(AS_public);
411 Method->setDescribedFunctionTemplate(TemplateMethod);
412 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000413
Douglas Gregoradb376e2012-02-14 22:28:59 +0000414 // Add parameters.
415 if (!Params.empty()) {
416 Method->setParams(Params);
417 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
418 const_cast<ParmVarDecl **>(Params.end()),
419 /*CheckParameterNames=*/false);
420
Aaron Ballman43b68be2014-03-07 17:50:17 +0000421 for (auto P : Method->params())
422 P->setOwningFunction(Method);
Douglas Gregoradb376e2012-02-14 22:28:59 +0000423 }
Richard Smith505df232012-07-22 23:45:10 +0000424
Eli Friedman7e346a82013-07-01 20:22:57 +0000425 Decl *ManglingContextDecl;
426 if (MangleNumberingContext *MCtx =
427 getCurrentMangleNumberContext(Class->getDeclContext(),
428 ManglingContextDecl)) {
429 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
430 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorb61e8092012-04-04 17:40:10 +0000431 }
432
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000433 return Method;
434}
435
Faisal Vali2b391ab2013-09-26 19:54:12 +0000436void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
437 CXXMethodDecl *CallOperator,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000438 SourceRange IntroducerRange,
439 LambdaCaptureDefault CaptureDefault,
James Dennettddd36ff2013-08-09 23:08:25 +0000440 SourceLocation CaptureDefaultLoc,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000441 bool ExplicitParams,
442 bool ExplicitResultType,
443 bool Mutable) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000444 LSI->CallOperator = CallOperator;
Faisal Valic1a6dc42013-10-23 16:10:50 +0000445 CXXRecordDecl *LambdaClass = CallOperator->getParent();
446 LSI->Lambda = LambdaClass;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000447 if (CaptureDefault == LCD_ByCopy)
448 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
449 else if (CaptureDefault == LCD_ByRef)
450 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettddd36ff2013-08-09 23:08:25 +0000451 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000452 LSI->IntroducerRange = IntroducerRange;
453 LSI->ExplicitParams = ExplicitParams;
454 LSI->Mutable = Mutable;
455
456 if (ExplicitResultType) {
Alp Toker314cc812014-01-25 16:55:45 +0000457 LSI->ReturnType = CallOperator->getReturnType();
458
Douglas Gregor621003e2012-02-14 21:20:44 +0000459 if (!LSI->ReturnType->isDependentType() &&
460 !LSI->ReturnType->isVoidType()) {
461 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
462 diag::err_lambda_incomplete_result)) {
463 // Do nothing.
Douglas Gregor621003e2012-02-14 21:20:44 +0000464 }
465 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000466 } else {
467 LSI->HasImplicitReturnType = true;
468 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000469}
470
471void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
472 LSI->finishedExplicitCaptures();
473}
474
Douglas Gregoradb376e2012-02-14 22:28:59 +0000475void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000476 // Introduce our parameters into the function scope
477 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
478 p < NumParams; ++p) {
479 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000480
481 // If this has an identifier, add it to the scope stack.
482 if (CurScope && Param->getIdentifier()) {
483 CheckShadow(CurScope, Param);
484
485 PushOnScopeChains(Param, CurScope);
486 }
487 }
488}
489
John McCalle4c11cc2013-03-09 00:54:31 +0000490/// If this expression is an enumerator-like expression of some type
491/// T, return the type T; otherwise, return null.
492///
493/// Pointer comparisons on the result here should always work because
494/// it's derived from either the parent of an EnumConstantDecl
495/// (i.e. the definition) or the declaration returned by
496/// EnumType::getDecl() (i.e. the definition).
497static EnumDecl *findEnumForBlockReturn(Expr *E) {
498 // An expression is an enumerator-like expression of type T if,
499 // ignoring parens and parens-like expressions:
500 E = E->IgnoreParens();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000501
John McCalle4c11cc2013-03-09 00:54:31 +0000502 // - it is an enumerator whose enum type is T or
503 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
504 if (EnumConstantDecl *D
505 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
506 return cast<EnumDecl>(D->getDeclContext());
507 }
508 return 0;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000509 }
510
John McCalle4c11cc2013-03-09 00:54:31 +0000511 // - it is a comma expression whose RHS is an enumerator-like
512 // expression of type T or
513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
514 if (BO->getOpcode() == BO_Comma)
515 return findEnumForBlockReturn(BO->getRHS());
516 return 0;
517 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000518
John McCalle4c11cc2013-03-09 00:54:31 +0000519 // - it is a statement-expression whose value expression is an
520 // enumerator-like expression of type T or
521 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
522 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
523 return findEnumForBlockReturn(last);
524 return 0;
525 }
526
527 // - it is a ternary conditional operator (not the GNU ?:
528 // extension) whose second and third operands are
529 // enumerator-like expressions of type T or
530 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
531 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
532 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
533 return ED;
534 return 0;
535 }
536
537 // (implicitly:)
538 // - it is an implicit integral conversion applied to an
539 // enumerator-like expression of type T or
540 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall1b4259b2013-05-08 03:34:22 +0000541 // We can sometimes see integral conversions in valid
542 // enumerator-like expressions.
John McCalle4c11cc2013-03-09 00:54:31 +0000543 if (ICE->getCastKind() == CK_IntegralCast)
544 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall1b4259b2013-05-08 03:34:22 +0000545
546 // Otherwise, just rely on the type.
John McCalle4c11cc2013-03-09 00:54:31 +0000547 }
548
549 // - it is an expression of that formal enum type.
550 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
551 return ET->getDecl();
552 }
553
554 // Otherwise, nope.
555 return 0;
556}
557
558/// Attempt to find a type T for which the returned expression of the
559/// given statement is an enumerator-like expression of that type.
560static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
561 if (Expr *retValue = ret->getRetValue())
562 return findEnumForBlockReturn(retValue);
563 return 0;
564}
565
566/// Attempt to find a common type T for which all of the returned
567/// expressions in a block are enumerator-like expressions of that
568/// type.
569static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
570 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
571
572 // Try to find one for the first return.
573 EnumDecl *ED = findEnumForBlockReturn(*i);
574 if (!ED) return 0;
575
576 // Check that the rest of the returns have the same enum.
577 for (++i; i != e; ++i) {
578 if (findEnumForBlockReturn(*i) != ED)
579 return 0;
580 }
581
582 // Never infer an anonymous enum type.
583 if (!ED->hasNameForLinkage()) return 0;
584
585 return ED;
586}
587
588/// Adjust the given return statements so that they formally return
589/// the given type. It should require, at most, an IntegralCast.
590static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
591 QualType returnType) {
592 for (ArrayRef<ReturnStmt*>::iterator
593 i = returns.begin(), e = returns.end(); i != e; ++i) {
594 ReturnStmt *ret = *i;
595 Expr *retValue = ret->getRetValue();
596 if (S.Context.hasSameType(retValue->getType(), returnType))
597 continue;
598
599 // Right now we only support integral fixup casts.
600 assert(returnType->isIntegralOrUnscopedEnumerationType());
601 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
602
603 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
604
605 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
606 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
607 E, /*base path*/ 0, VK_RValue);
608 if (cleanups) {
609 cleanups->setSubExpr(E);
610 } else {
611 ret->setRetValue(E);
Jordan Rosed39e5f12012-07-02 21:19:23 +0000612 }
613 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000614}
615
616void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000617 assert(CSI.HasImplicitReturnType);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000618 // If it was ever a placeholder, it had to been deduced to DependentTy.
619 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rosed39e5f12012-07-02 21:19:23 +0000620
John McCalle4c11cc2013-03-09 00:54:31 +0000621 // C++ Core Issue #975, proposed resolution:
622 // If a lambda-expression does not include a trailing-return-type,
623 // it is as if the trailing-return-type denotes the following type:
624 // - if there are no return statements in the compound-statement,
625 // or all return statements return either an expression of type
626 // void or no expression or braced-init-list, the type void;
627 // - otherwise, if all return statements return an expression
628 // and the types of the returned expressions after
629 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
630 // array-to-pointer conversion (4.2 [conv.array]), and
631 // function-to-pointer conversion (4.3 [conv.func]) are the
632 // same, that common type;
633 // - otherwise, the program is ill-formed.
634 //
635 // In addition, in blocks in non-C++ modes, if all of the return
636 // statements are enumerator-like expressions of some type T, where
637 // T has a name for linkage, then we infer the return type of the
638 // block to be that type.
639
Jordan Rosed39e5f12012-07-02 21:19:23 +0000640 // First case: no return statements, implicit void return type.
641 ASTContext &Ctx = getASTContext();
642 if (CSI.Returns.empty()) {
643 // It's possible there were simply no /valid/ return statements.
644 // In this case, the first one we found may have at least given us a type.
645 if (CSI.ReturnType.isNull())
646 CSI.ReturnType = Ctx.VoidTy;
647 return;
648 }
649
650 // Second case: at least one return statement has dependent type.
651 // Delay type checking until instantiation.
652 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000653 if (CSI.ReturnType->isDependentType())
Jordan Rosed39e5f12012-07-02 21:19:23 +0000654 return;
655
John McCalle4c11cc2013-03-09 00:54:31 +0000656 // Try to apply the enum-fuzz rule.
657 if (!getLangOpts().CPlusPlus) {
658 assert(isa<BlockScopeInfo>(CSI));
659 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
660 if (ED) {
661 CSI.ReturnType = Context.getTypeDeclType(ED);
662 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
663 return;
664 }
665 }
666
Jordan Rosed39e5f12012-07-02 21:19:23 +0000667 // Third case: only one return statement. Don't bother doing extra work!
668 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
669 E = CSI.Returns.end();
670 if (I+1 == E)
671 return;
672
673 // General case: many return statements.
674 // Check that they all have compatible return types.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000675
676 // We require the return types to strictly match here.
John McCalle4c11cc2013-03-09 00:54:31 +0000677 // Note that we've already done the required promotions as part of
678 // processing the return statement.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000679 for (; I != E; ++I) {
680 const ReturnStmt *RS = *I;
681 const Expr *RetE = RS->getRetValue();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000682
John McCalle4c11cc2013-03-09 00:54:31 +0000683 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
684 if (Context.hasSameType(ReturnType, CSI.ReturnType))
685 continue;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000686
John McCalle4c11cc2013-03-09 00:54:31 +0000687 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
688 // TODO: It's possible that the *first* return is the divergent one.
689 Diag(RS->getLocStart(),
690 diag::err_typecheck_missing_return_type_incompatible)
691 << ReturnType << CSI.ReturnType
692 << isa<LambdaScopeInfo>(CSI);
693 // Continue iterating so that we keep emitting diagnostics.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000694 }
695}
696
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000697QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
698 bool ByRef,
699 IdentifierInfo *Id,
700 Expr *&Init) {
701
702 // We do not need to distinguish between direct-list-initialization
703 // and copy-list-initialization here, because we will always deduce
704 // std::initializer_list<T>, and direct- and copy-list-initialization
705 // always behave the same for such a type.
706 // FIXME: We should model whether an '=' was present.
707 const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
708
709 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
710 // deduce against.
Richard Smithba71c082013-05-16 06:20:58 +0000711 QualType DeductType = Context.getAutoDeductType();
712 TypeLocBuilder TLB;
713 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
714 if (ByRef) {
715 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
716 assert(!DeductType.isNull() && "can't build reference to auto");
717 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
718 }
Eli Friedman7152fbe2013-06-07 20:31:48 +0000719 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smithba71c082013-05-16 06:20:58 +0000720
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000721 // Are we a non-list direct initialization?
722 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
723
724 Expr *DeduceInit = Init;
725 // Initializer could be a C++ direct-initializer. Deduction only works if it
726 // contains exactly one expression.
727 if (CXXDirectInit) {
728 if (CXXDirectInit->getNumExprs() == 0) {
729 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
730 << DeclarationName(Id) << TSI->getType() << Loc;
731 return QualType();
732 } else if (CXXDirectInit->getNumExprs() > 1) {
733 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
734 diag::err_init_capture_multiple_expressions)
735 << DeclarationName(Id) << TSI->getType() << Loc;
736 return QualType();
737 } else {
738 DeduceInit = CXXDirectInit->getExpr(0);
739 }
740 }
741
742 // Now deduce against the initialization expression and store the deduced
743 // type below.
744 QualType DeducedType;
745 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
746 if (isa<InitListExpr>(Init))
747 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
748 << DeclarationName(Id)
749 << (DeduceInit->getType().isNull() ? TSI->getType()
750 : DeduceInit->getType())
751 << DeduceInit->getSourceRange();
752 else
753 Diag(Loc, diag::err_init_capture_deduction_failure)
754 << DeclarationName(Id) << TSI->getType()
755 << (DeduceInit->getType().isNull() ? TSI->getType()
756 : DeduceInit->getType())
757 << DeduceInit->getSourceRange();
758 }
759 if (DeducedType.isNull())
760 return QualType();
761
762 // Perform initialization analysis and ensure any implicit conversions
763 // (such as lvalue-to-rvalue) are enforced.
764 InitializedEntity Entity =
765 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
766 InitializationKind Kind =
767 IsDirectInit
768 ? (CXXDirectInit ? InitializationKind::CreateDirect(
769 Loc, Init->getLocStart(), Init->getLocEnd())
770 : InitializationKind::CreateDirectList(Loc))
771 : InitializationKind::CreateCopy(Loc, Init->getLocStart());
772
773 MultiExprArg Args = Init;
774 if (CXXDirectInit)
775 Args =
776 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
777 QualType DclT;
778 InitializationSequence InitSeq(*this, Entity, Kind, Args);
779 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
780
781 if (Result.isInvalid())
782 return QualType();
783 Init = Result.takeAs<Expr>();
784
785 // The init-capture initialization is a full-expression that must be
786 // processed as one before we enter the declcontext of the lambda's
787 // call-operator.
788 Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
789 /*IsConstexpr*/ false,
790 /*IsLambdaInitCaptureInitalizer*/ true);
791 if (Result.isInvalid())
792 return QualType();
793
794 Init = Result.takeAs<Expr>();
795 return DeducedType;
796}
797
798VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
799 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
800
801 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
802 Loc);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000803 // Create a dummy variable representing the init-capture. This is not actually
804 // used as a variable, and only exists as a way to name and refer to the
805 // init-capture.
806 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith75e3f692013-09-28 04:31:26 +0000807 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000808 Loc, Id, InitCaptureType, TSI, SC_Auto);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000809 NewVD->setInitCapture(true);
810 NewVD->setReferenced(true);
811 NewVD->markUsed(Context);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000812 NewVD->setInit(Init);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000813 return NewVD;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000814
Richard Smithbb13c9a2013-09-28 04:02:39 +0000815}
Richard Smithba71c082013-05-16 06:20:58 +0000816
Richard Smithbb13c9a2013-09-28 04:02:39 +0000817FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
818 FieldDecl *Field = FieldDecl::Create(
819 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
820 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
821 Field->setImplicit(true);
822 Field->setAccess(AS_private);
823 LSI->Lambda->addDecl(Field);
Richard Smithba71c082013-05-16 06:20:58 +0000824
Richard Smithbb13c9a2013-09-28 04:02:39 +0000825 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
826 /*isNested*/false, Var->getLocation(), SourceLocation(),
827 Var->getType(), Var->getInit());
828 return Field;
Richard Smithba71c082013-05-16 06:20:58 +0000829}
830
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000831void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Vali2b391ab2013-09-26 19:54:12 +0000832 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregor680e9e02012-02-21 19:11:17 +0000833 // Determine if we're within a context where we know that the lambda will
834 // be dependent, because there are template parameters in scope.
835 bool KnownDependent = false;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000836 LambdaScopeInfo *const LSI = getCurLambda();
837 assert(LSI && "LambdaScopeInfo should be on stack!");
838 TemplateParameterList *TemplateParams =
839 getGenericLambdaTemplateParameterList(LSI, *this);
840
841 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
842 // Since we have our own TemplateParams, so check if an outer scope
843 // has template params, only then are we in a dependent scope.
844 if (TemplateParams) {
845 TmplScope = TmplScope->getParent();
846 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
847 }
848 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregor680e9e02012-02-21 19:11:17 +0000849 KnownDependent = true;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000850 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000851 // Determine the signature of the call operator.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000852 TypeSourceInfo *MethodTyInfo;
853 bool ExplicitParams = true;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000854 bool ExplicitResultType = true;
Richard Smith2589b9802012-07-25 03:56:55 +0000855 bool ContainsUnexpandedParameterPack = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000856 SourceLocation EndLoc;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000857 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000858 if (ParamInfo.getNumTypeObjects() == 0) {
859 // C++11 [expr.prim.lambda]p4:
860 // If a lambda-expression does not include a lambda-declarator, it is as
861 // if the lambda-declarator were ().
Reid Kleckner78af0702013-08-27 23:08:25 +0000862 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
863 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smith5e580292012-02-10 09:58:53 +0000864 EPI.HasTrailingReturn = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000865 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000866 // C++1y [expr.prim.lambda]:
867 // The lambda return type is 'auto', which is replaced by the
868 // trailing-return type if provided and/or deduced from 'return'
869 // statements
870 // We don't do this before C++1y, because we don't support deduced return
871 // types there.
872 QualType DefaultTypeForNoTrailingReturn =
873 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
874 : Context.DependentTy;
875 QualType MethodTy =
876 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000877 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
878 ExplicitParams = false;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000879 ExplicitResultType = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000880 EndLoc = Intro.Range.getEnd();
881 } else {
882 assert(ParamInfo.isFunctionDeclarator() &&
883 "lambda-declarator is a function");
884 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith4db51c22013-09-25 05:02:54 +0000885
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000886 // C++11 [expr.prim.lambda]p5:
887 // This function call operator is declared const (9.3.1) if and only if
888 // the lambda-expression's parameter-declaration-clause is not followed
889 // by mutable. It is neither virtual nor declared volatile. [...]
890 if (!FTI.hasMutableQualifier())
891 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000892
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000893 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000894 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000895 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith4db51c22013-09-25 05:02:54 +0000896
897 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000898
Alp Tokerc5350722014-02-26 22:27:52 +0000899 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
900 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
Eli Friedman8f5e9832012-09-20 01:40:23 +0000901 // Empty arg list, don't push any params.
Eli Friedman8f5e9832012-09-20 01:40:23 +0000902 } else {
Alp Tokerc5350722014-02-26 22:27:52 +0000903 Params.reserve(FTI.NumParams);
904 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
905 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
Eli Friedman8f5e9832012-09-20 01:40:23 +0000906 }
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000907
908 // Check for unexpanded parameter packs in the method type.
Richard Smith2589b9802012-07-25 03:56:55 +0000909 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
910 ContainsUnexpandedParameterPack = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000911 }
Eli Friedmand564afb2012-09-19 01:18:11 +0000912
913 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000914 KnownDependent, Intro.Default);
Eli Friedmand564afb2012-09-19 01:18:11 +0000915
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000916 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregoradb376e2012-02-14 22:28:59 +0000917 MethodTyInfo, EndLoc, Params);
Douglas Gregoradb376e2012-02-14 22:28:59 +0000918 if (ExplicitParams)
919 CheckCXXDefaultArguments(Method);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000920
Bill Wendling44426052012-12-20 19:22:21 +0000921 // Attributes on the lambda apply to the method.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000922 ProcessDeclAttributes(CurScope, Method, ParamInfo);
923
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000924 // Introduce the function call operator as the current declaration context.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000925 PushDeclContext(CurScope, Method);
926
Faisal Vali2b391ab2013-09-26 19:54:12 +0000927 // Build the lambda scope.
928 buildLambdaScope(LSI, Method,
James Dennettddd36ff2013-08-09 23:08:25 +0000929 Intro.Range,
930 Intro.Default, Intro.DefaultLoc,
931 ExplicitParams,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000932 ExplicitResultType,
David Blaikief5697e52012-08-10 00:55:35 +0000933 !Method->isConst());
Richard Smithba71c082013-05-16 06:20:58 +0000934
Richard Smith3d584b02014-02-06 21:49:08 +0000935 // C++11 [expr.prim.lambda]p9:
936 // A lambda-expression whose smallest enclosing scope is a block scope is a
937 // local lambda expression; any other lambda expression shall not have a
938 // capture-default or simple-capture in its lambda-introducer.
939 //
940 // For simple-captures, this is covered by the check below that any named
941 // entity is a variable that can be captured.
942 //
943 // For DR1632, we also allow a capture-default in any context where we can
944 // odr-use 'this' (in particular, in a default initializer for a non-static
945 // data member).
946 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
947 (getCurrentThisType().isNull() ||
948 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
949 /*BuildAndDiagnose*/false)))
950 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
951
Richard Smithba71c082013-05-16 06:20:58 +0000952 // Distinct capture names, for diagnostics.
953 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
954
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000955 // Handle explicit captures.
Douglas Gregora1bffa22012-02-10 17:46:20 +0000956 SourceLocation PrevCaptureLoc
957 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper2341c0d2013-07-04 03:08:24 +0000958 for (SmallVectorImpl<LambdaCapture>::const_iterator
959 C = Intro.Captures.begin(),
960 E = Intro.Captures.end();
961 C != E;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000962 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000963 if (C->Kind == LCK_This) {
964 // C++11 [expr.prim.lambda]p8:
965 // An identifier or this shall not appear more than once in a
966 // lambda-capture.
967 if (LSI->isCXXThisCaptured()) {
968 Diag(C->Loc, diag::err_capture_more_than_once)
969 << "'this'"
Douglas Gregora1bffa22012-02-10 17:46:20 +0000970 << SourceRange(LSI->getCXXThisCapture().getLocation())
971 << FixItHint::CreateRemoval(
972 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000973 continue;
974 }
975
976 // C++11 [expr.prim.lambda]p8:
977 // If a lambda-capture includes a capture-default that is =, the
978 // lambda-capture shall not contain this [...].
979 if (Intro.Default == LCD_ByCopy) {
Douglas Gregora1bffa22012-02-10 17:46:20 +0000980 Diag(C->Loc, diag::err_this_capture_with_copy_default)
981 << FixItHint::CreateRemoval(
982 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000983 continue;
984 }
985
986 // C++11 [expr.prim.lambda]p12:
987 // If this is captured by a local lambda expression, its nearest
988 // enclosing function shall be a non-static member function.
989 QualType ThisCaptureType = getCurrentThisType();
990 if (ThisCaptureType.isNull()) {
991 Diag(C->Loc, diag::err_this_capture) << true;
992 continue;
993 }
994
995 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
996 continue;
997 }
998
Richard Smithba71c082013-05-16 06:20:58 +0000999 assert(C->Id && "missing identifier for capture");
1000
Richard Smith21b3ab42013-05-09 21:36:41 +00001001 if (C->Init.isInvalid())
1002 continue;
Richard Smithba71c082013-05-16 06:20:58 +00001003
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001004 VarDecl *Var = 0;
Richard Smithbb13c9a2013-09-28 04:02:39 +00001005 if (C->Init.isUsable()) {
Richard Smith5b013f52013-09-28 05:38:27 +00001006 Diag(C->Loc, getLangOpts().CPlusPlus1y
1007 ? diag::warn_cxx11_compat_init_capture
1008 : diag::ext_init_capture);
1009
Richard Smithba71c082013-05-16 06:20:58 +00001010 if (C->Init.get()->containsUnexpandedParameterPack())
1011 ContainsUnexpandedParameterPack = true;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001012 // If the initializer expression is usable, but the InitCaptureType
1013 // is not, then an error has occurred - so ignore the capture for now.
1014 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1015 // FIXME: we should create the init capture variable and mark it invalid
1016 // in this case.
1017 if (C->InitCaptureType.get().isNull())
1018 continue;
1019 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1020 C->Id, C->Init.take());
Richard Smithba71c082013-05-16 06:20:58 +00001021 // C++1y [expr.prim.lambda]p11:
Richard Smithbb13c9a2013-09-28 04:02:39 +00001022 // An init-capture behaves as if it declares and explicitly
1023 // captures a variable [...] whose declarative region is the
1024 // lambda-expression's compound-statement
1025 if (Var)
1026 PushOnScopeChains(Var, CurScope, false);
1027 } else {
1028 // C++11 [expr.prim.lambda]p8:
1029 // If a lambda-capture includes a capture-default that is &, the
1030 // identifiers in the lambda-capture shall not be preceded by &.
1031 // If a lambda-capture includes a capture-default that is =, [...]
1032 // each identifier it contains shall be preceded by &.
1033 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1034 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1035 << FixItHint::CreateRemoval(
1036 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001037 continue;
Richard Smithbb13c9a2013-09-28 04:02:39 +00001038 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1039 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1040 << FixItHint::CreateRemoval(
1041 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1042 continue;
1043 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001044
Richard Smithbb13c9a2013-09-28 04:02:39 +00001045 // C++11 [expr.prim.lambda]p10:
1046 // The identifiers in a capture-list are looked up using the usual
1047 // rules for unqualified name lookup (3.4.1)
1048 DeclarationNameInfo Name(C->Id, C->Loc);
1049 LookupResult R(*this, Name, LookupOrdinaryName);
1050 LookupName(R, CurScope);
1051 if (R.isAmbiguous())
1052 continue;
1053 if (R.empty()) {
1054 // FIXME: Disable corrections that would add qualification?
1055 CXXScopeSpec ScopeSpec;
1056 DeclFilterCCC<VarDecl> Validator;
1057 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1058 continue;
1059 }
1060
1061 Var = R.getAsSingle<VarDecl>();
1062 }
Richard Smithba71c082013-05-16 06:20:58 +00001063
1064 // C++11 [expr.prim.lambda]p8:
1065 // An identifier or this shall not appear more than once in a
1066 // lambda-capture.
1067 if (!CaptureNames.insert(C->Id)) {
1068 if (Var && LSI->isCaptured(Var)) {
1069 Diag(C->Loc, diag::err_capture_more_than_once)
1070 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1071 << FixItHint::CreateRemoval(
1072 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1073 } else
Richard Smithbb13c9a2013-09-28 04:02:39 +00001074 // Previous capture captured something different (one or both was
1075 // an init-cpature): no fixit.
Richard Smithba71c082013-05-16 06:20:58 +00001076 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1077 continue;
1078 }
1079
1080 // C++11 [expr.prim.lambda]p10:
1081 // [...] each such lookup shall find a variable with automatic storage
1082 // duration declared in the reaching scope of the local lambda expression.
1083 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001084 if (!Var) {
1085 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1086 continue;
1087 }
1088
Eli Friedmane979db12012-09-18 21:11:30 +00001089 // Ignore invalid decls; they'll just confuse the code later.
1090 if (Var->isInvalidDecl())
1091 continue;
1092
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001093 if (!Var->hasLocalStorage()) {
1094 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1095 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1096 continue;
1097 }
1098
Douglas Gregor3e308b12012-02-14 19:27:52 +00001099 // C++11 [expr.prim.lambda]p23:
1100 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1101 SourceLocation EllipsisLoc;
1102 if (C->EllipsisLoc.isValid()) {
1103 if (Var->isParameterPack()) {
1104 EllipsisLoc = C->EllipsisLoc;
1105 } else {
1106 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1107 << SourceRange(C->Loc);
1108
1109 // Just ignore the ellipsis.
1110 }
1111 } else if (Var->isParameterPack()) {
Richard Smith2589b9802012-07-25 03:56:55 +00001112 ContainsUnexpandedParameterPack = true;
Douglas Gregor3e308b12012-02-14 19:27:52 +00001113 }
Richard Smithbb13c9a2013-09-28 04:02:39 +00001114
1115 if (C->Init.isUsable()) {
1116 buildInitCaptureField(LSI, Var);
1117 } else {
1118 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1119 TryCapture_ExplicitByVal;
1120 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1121 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001122 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001123 finishLambdaExplicitCaptures(LSI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001124
Richard Smith2589b9802012-07-25 03:56:55 +00001125 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1126
Douglas Gregoradb376e2012-02-14 22:28:59 +00001127 // Add lambda parameters into scope.
1128 addLambdaParameters(Method, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001129
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001130 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001131 // cleanups from the enclosing full-expression.
1132 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001133}
1134
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001135void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1136 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001137 // Leave the expression-evaluation context.
1138 DiscardCleanupsInEvaluationContext();
1139 PopExpressionEvaluationContext();
1140
1141 // Leave the context of the lambda.
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001142 if (!IsInstantiation)
1143 PopDeclContext();
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001144
1145 // Finalize the lambda.
1146 LambdaScopeInfo *LSI = getCurLambda();
1147 CXXRecordDecl *Class = LSI->Lambda;
1148 Class->setInvalidDecl();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001149 SmallVector<Decl*, 4> Fields;
1150 for (RecordDecl::field_iterator i = Class->field_begin(),
1151 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001152 Fields.push_back(*i);
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001153 ActOnFields(0, Class->getLocation(), Class, Fields,
1154 SourceLocation(), SourceLocation(), 0);
1155 CheckCompletedCXXClass(Class);
1156
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001157 PopFunctionScopeInfo();
1158}
1159
Douglas Gregor13f09b42012-02-15 22:00:51 +00001160/// \brief Add a lambda's conversion to function pointer, as described in
1161/// C++11 [expr.prim.lambda]p6.
1162static void addFunctionPointerConversion(Sema &S,
1163 SourceRange IntroducerRange,
1164 CXXRecordDecl *Class,
1165 CXXMethodDecl *CallOperator) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00001166 // Add the conversion to function pointer.
Faisal Vali66605d42013-10-24 01:05:22 +00001167 const FunctionProtoType *CallOpProto =
1168 CallOperator->getType()->getAs<FunctionProtoType>();
1169 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1170 CallOpProto->getExtProtoInfo();
1171 QualType PtrToFunctionTy;
1172 QualType InvokerFunctionTy;
Douglas Gregor13f09b42012-02-15 22:00:51 +00001173 {
Faisal Vali66605d42013-10-24 01:05:22 +00001174 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
Reid Kleckner78af0702013-08-27 23:08:25 +00001175 CallingConv CC = S.Context.getDefaultCallingConvention(
Faisal Vali66605d42013-10-24 01:05:22 +00001176 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1177 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1178 InvokerExtInfo.TypeQuals = 0;
1179 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1180 "Lambda's call operator should not have a reference qualifier");
Alp Toker9cacbab2014-01-20 20:26:09 +00001181 InvokerFunctionTy =
Alp Toker314cc812014-01-25 16:55:45 +00001182 S.Context.getFunctionType(CallOpProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001183 CallOpProto->getParamTypes(), InvokerExtInfo);
Faisal Vali66605d42013-10-24 01:05:22 +00001184 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001185 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001186
Faisal Vali66605d42013-10-24 01:05:22 +00001187 // Create the type of the conversion function.
1188 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1189 S.Context.getDefaultCallingConvention(
Reid Kleckner78af0702013-08-27 23:08:25 +00001190 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Faisal Vali66605d42013-10-24 01:05:22 +00001191 // The conversion function is always const.
1192 ConvExtInfo.TypeQuals = Qualifiers::Const;
1193 QualType ConvTy =
1194 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
Reid Kleckner78af0702013-08-27 23:08:25 +00001195
Douglas Gregor13f09b42012-02-15 22:00:51 +00001196 SourceLocation Loc = IntroducerRange.getBegin();
Faisal Vali66605d42013-10-24 01:05:22 +00001197 DeclarationName ConversionName
Douglas Gregor13f09b42012-02-15 22:00:51 +00001198 = S.Context.DeclarationNames.getCXXConversionFunctionName(
Faisal Vali66605d42013-10-24 01:05:22 +00001199 S.Context.getCanonicalType(PtrToFunctionTy));
1200 DeclarationNameLoc ConvNameLoc;
1201 // Construct a TypeSourceInfo for the conversion function, and wire
1202 // all the parameters appropriately for the FunctionProtoTypeLoc
1203 // so that everything works during transformation/instantiation of
1204 // generic lambdas.
1205 // The main reason for wiring up the parameters of the conversion
1206 // function with that of the call operator is so that constructs
1207 // like the following work:
1208 // auto L = [](auto b) { <-- 1
1209 // return [](auto a) -> decltype(a) { <-- 2
1210 // return a;
1211 // };
1212 // };
1213 // int (*fp)(int) = L(5);
1214 // Because the trailing return type can contain DeclRefExprs that refer
1215 // to the original call operator's variables, we hijack the call
1216 // operators ParmVarDecls below.
1217 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1218 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1219 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1220
1221 // The conversion function is a conversion to a pointer-to-function.
1222 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1223 FunctionProtoTypeLoc ConvTL =
1224 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1225 // Get the result of the conversion function which is a pointer-to-function.
1226 PointerTypeLoc PtrToFunctionTL =
Alp Toker42a16a62014-01-25 23:51:36 +00001227 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
Faisal Vali66605d42013-10-24 01:05:22 +00001228 // Do the same for the TypeSourceInfo that is used to name the conversion
1229 // operator.
1230 PointerTypeLoc ConvNamePtrToFunctionTL =
1231 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1232
1233 // Get the underlying function types that the conversion function will
1234 // be converting to (should match the type of the call operator).
1235 FunctionProtoTypeLoc CallOpConvTL =
1236 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1237 FunctionProtoTypeLoc CallOpConvNameTL =
1238 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1239
1240 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1241 // These parameter's are essentially used to transform the name and
1242 // the type of the conversion operator. By using the same parameters
1243 // as the call operator's we don't have to fix any back references that
1244 // the trailing return type of the call operator's uses (such as
1245 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1246 // - we can simply use the return type of the call operator, and
1247 // everything should work.
1248 SmallVector<ParmVarDecl *, 4> InvokerParams;
1249 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1250 ParmVarDecl *From = CallOperator->getParamDecl(I);
1251
1252 InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1253 // Temporarily add to the TU. This is set to the invoker below.
1254 S.Context.getTranslationUnitDecl(),
1255 From->getLocStart(),
1256 From->getLocation(),
1257 From->getIdentifier(),
1258 From->getType(),
1259 From->getTypeSourceInfo(),
1260 From->getStorageClass(),
1261 /*DefaultArg=*/0));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001262 CallOpConvTL.setParam(I, From);
1263 CallOpConvNameTL.setParam(I, From);
Faisal Vali66605d42013-10-24 01:05:22 +00001264 }
1265
Douglas Gregor13f09b42012-02-15 22:00:51 +00001266 CXXConversionDecl *Conversion
1267 = CXXConversionDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001268 DeclarationNameInfo(ConversionName,
1269 Loc, ConvNameLoc),
Douglas Gregor13f09b42012-02-15 22:00:51 +00001270 ConvTy,
Faisal Vali66605d42013-10-24 01:05:22 +00001271 ConvTSI,
Eli Friedman8f54e132013-06-13 19:39:48 +00001272 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor13f09b42012-02-15 22:00:51 +00001273 /*isConstexpr=*/false,
1274 CallOperator->getBody()->getLocEnd());
1275 Conversion->setAccess(AS_public);
1276 Conversion->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001277
1278 if (Class->isGenericLambda()) {
1279 // Create a template version of the conversion operator, using the template
1280 // parameter list of the function call operator.
1281 FunctionTemplateDecl *TemplateCallOperator =
1282 CallOperator->getDescribedFunctionTemplate();
1283 FunctionTemplateDecl *ConversionTemplate =
1284 FunctionTemplateDecl::Create(S.Context, Class,
Faisal Vali66605d42013-10-24 01:05:22 +00001285 Loc, ConversionName,
Faisal Vali571df122013-09-29 08:45:24 +00001286 TemplateCallOperator->getTemplateParameters(),
1287 Conversion);
1288 ConversionTemplate->setAccess(AS_public);
1289 ConversionTemplate->setImplicit(true);
1290 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1291 Class->addDecl(ConversionTemplate);
1292 } else
1293 Class->addDecl(Conversion);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001294 // Add a non-static member function that will be the result of
1295 // the conversion with a certain unique ID.
Faisal Vali66605d42013-10-24 01:05:22 +00001296 DeclarationName InvokerName = &S.Context.Idents.get(
1297 getLambdaStaticInvokerName());
Faisal Vali571df122013-09-29 08:45:24 +00001298 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1299 // we should get a prebuilt TrivialTypeSourceInfo from Context
1300 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1301 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1302 // loop below and then use its Params to set Invoke->setParams(...) below.
1303 // This would avoid the 'const' qualifier of the calloperator from
1304 // contaminating the type of the invoker, which is currently adjusted
Faisal Vali66605d42013-10-24 01:05:22 +00001305 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1306 // trailing return type of the invoker would require a visitor to rebuild
1307 // the trailing return type and adjusting all back DeclRefExpr's to refer
1308 // to the new static invoker parameters - not the call operator's.
Douglas Gregor355efbb2012-02-17 03:02:34 +00001309 CXXMethodDecl *Invoke
1310 = CXXMethodDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001311 DeclarationNameInfo(InvokerName, Loc),
1312 InvokerFunctionTy,
1313 CallOperator->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001314 SC_Static, /*IsInline=*/true,
Douglas Gregor355efbb2012-02-17 03:02:34 +00001315 /*IsConstexpr=*/false,
1316 CallOperator->getBody()->getLocEnd());
Faisal Vali66605d42013-10-24 01:05:22 +00001317 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1318 InvokerParams[I]->setOwningFunction(Invoke);
1319 Invoke->setParams(InvokerParams);
Douglas Gregor355efbb2012-02-17 03:02:34 +00001320 Invoke->setAccess(AS_private);
1321 Invoke->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001322 if (Class->isGenericLambda()) {
1323 FunctionTemplateDecl *TemplateCallOperator =
1324 CallOperator->getDescribedFunctionTemplate();
1325 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
Faisal Vali66605d42013-10-24 01:05:22 +00001326 S.Context, Class, Loc, InvokerName,
Faisal Vali571df122013-09-29 08:45:24 +00001327 TemplateCallOperator->getTemplateParameters(),
1328 Invoke);
1329 StaticInvokerTemplate->setAccess(AS_private);
1330 StaticInvokerTemplate->setImplicit(true);
1331 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1332 Class->addDecl(StaticInvokerTemplate);
1333 } else
1334 Class->addDecl(Invoke);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001335}
1336
Douglas Gregor33e863c2012-02-15 22:08:38 +00001337/// \brief Add a lambda's conversion to block pointer.
1338static void addBlockPointerConversion(Sema &S,
1339 SourceRange IntroducerRange,
1340 CXXRecordDecl *Class,
1341 CXXMethodDecl *CallOperator) {
1342 const FunctionProtoType *Proto
1343 = CallOperator->getType()->getAs<FunctionProtoType>();
1344 QualType BlockPtrTy;
1345 {
1346 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1347 ExtInfo.TypeQuals = 0;
Reid Kleckner896b32f2013-06-10 20:51:09 +00001348 QualType FunctionTy = S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00001349 Proto->getReturnType(), Proto->getParamTypes(), ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001350 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1351 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001352
1353 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1354 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregor33e863c2012-02-15 22:08:38 +00001355 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001356 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001357
1358 SourceLocation Loc = IntroducerRange.getBegin();
1359 DeclarationName Name
1360 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1361 S.Context.getCanonicalType(BlockPtrTy));
1362 DeclarationNameLoc NameLoc;
1363 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1364 CXXConversionDecl *Conversion
1365 = CXXConversionDecl::Create(S.Context, Class, Loc,
1366 DeclarationNameInfo(Name, Loc, NameLoc),
1367 ConvTy,
1368 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedmanef102822013-06-13 20:56:27 +00001369 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor33e863c2012-02-15 22:08:38 +00001370 /*isConstexpr=*/false,
1371 CallOperator->getBody()->getLocEnd());
1372 Conversion->setAccess(AS_public);
1373 Conversion->setImplicit(true);
1374 Class->addDecl(Conversion);
1375}
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001376
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001377ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor63798542012-02-20 19:44:39 +00001378 Scope *CurScope,
Douglas Gregor63798542012-02-20 19:44:39 +00001379 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001380 // Collect information from the lambda scope.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001381 SmallVector<LambdaExpr::Capture, 4> Captures;
1382 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001383 LambdaCaptureDefault CaptureDefault;
James Dennettddd36ff2013-08-09 23:08:25 +00001384 SourceLocation CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001385 CXXRecordDecl *Class;
Douglas Gregor12695102012-02-10 08:36:38 +00001386 CXXMethodDecl *CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001387 SourceRange IntroducerRange;
1388 bool ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001389 bool ExplicitResultType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001390 bool LambdaExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001391 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001392 SmallVector<VarDecl *, 4> ArrayIndexVars;
1393 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001394 {
1395 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregor12695102012-02-10 08:36:38 +00001396 CallOperator = LSI->CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001397 Class = LSI->Lambda;
1398 IntroducerRange = LSI->IntroducerRange;
1399 ExplicitParams = LSI->ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001400 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001401 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001402 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor54fcea62012-02-13 16:35:30 +00001403 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1404 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1405
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001406 // Translate captures.
1407 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1408 LambdaScopeInfo::Capture From = LSI->Captures[I];
1409 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1410 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1411
1412 // Handle 'this' capture.
1413 if (From.isThisCapture()) {
1414 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1415 IsImplicit,
1416 LCK_This));
1417 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1418 getCurrentThisType(),
1419 /*isImplicit=*/true));
1420 continue;
1421 }
1422
1423 VarDecl *Var = From.getVariable();
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001424 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1425 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregor3e308b12012-02-14 19:27:52 +00001426 Kind, Var, From.getEllipsisLoc()));
Richard Smithba71c082013-05-16 06:20:58 +00001427 CaptureInits.push_back(From.getInitExpr());
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001428 }
1429
1430 switch (LSI->ImpCaptureStyle) {
1431 case CapturingScopeInfo::ImpCap_None:
1432 CaptureDefault = LCD_None;
1433 break;
1434
1435 case CapturingScopeInfo::ImpCap_LambdaByval:
1436 CaptureDefault = LCD_ByCopy;
1437 break;
1438
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001439 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001440 case CapturingScopeInfo::ImpCap_LambdaByref:
1441 CaptureDefault = LCD_ByRef;
1442 break;
1443
1444 case CapturingScopeInfo::ImpCap_Block:
1445 llvm_unreachable("block capture in lambda");
1446 break;
1447 }
James Dennettddd36ff2013-08-09 23:08:25 +00001448 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001449
Douglas Gregor73456262012-02-09 10:18:50 +00001450 // C++11 [expr.prim.lambda]p4:
1451 // If a lambda-expression does not include a
1452 // trailing-return-type, it is as if the trailing-return-type
1453 // denotes the following type:
Richard Smith4db51c22013-09-25 05:02:54 +00001454 //
1455 // Skip for C++1y return type deduction semantics which uses
1456 // different machinery.
1457 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor73456262012-02-09 10:18:50 +00001458 // FIXME: Assumes current resolution to core issue 975.
Richard Smith4db51c22013-09-25 05:02:54 +00001459 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rosed39e5f12012-07-02 21:19:23 +00001460 deduceClosureReturnType(*LSI);
1461
Douglas Gregor73456262012-02-09 10:18:50 +00001462 // - if there are no return statements in the
1463 // compound-statement, or all return statements return
1464 // either an expression of type void or no expression or
1465 // braced-init-list, the type void;
1466 if (LSI->ReturnType.isNull()) {
1467 LSI->ReturnType = Context.VoidTy;
Douglas Gregor73456262012-02-09 10:18:50 +00001468 }
1469
1470 // Create a function type with the inferred return type.
1471 const FunctionProtoType *Proto
1472 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner896b32f2013-06-10 20:51:09 +00001473 QualType FunctionTy = Context.getFunctionType(
Alp Toker9cacbab2014-01-20 20:26:09 +00001474 LSI->ReturnType, Proto->getParamTypes(), Proto->getExtProtoInfo());
Douglas Gregor73456262012-02-09 10:18:50 +00001475 CallOperator->setType(FunctionTy);
1476 }
Douglas Gregor1a22d282012-02-12 17:34:23 +00001477 // C++ [expr.prim.lambda]p7:
1478 // The lambda-expression's compound-statement yields the
1479 // function-body (8.4) of the function call operator [...].
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001480 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor1a22d282012-02-12 17:34:23 +00001481 CallOperator->setLexicalDeclContext(Class);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001482 Decl *TemplateOrNonTemplateCallOperatorDecl =
1483 CallOperator->getDescribedFunctionTemplate()
1484 ? CallOperator->getDescribedFunctionTemplate()
1485 : cast<Decl>(CallOperator);
1486
1487 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1488 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1489
Douglas Gregor5dbc14f2012-02-21 20:05:31 +00001490 PopExpressionEvaluationContext();
Douglas Gregor1a22d282012-02-12 17:34:23 +00001491
Douglas Gregor04bbab52012-02-10 16:13:20 +00001492 // C++11 [expr.prim.lambda]p6:
1493 // The closure type for a lambda-expression with no lambda-capture
1494 // has a public non-virtual non-explicit const conversion function
1495 // to pointer to function having the same parameter and return
1496 // types as the closure type's function call operator.
Douglas Gregor13f09b42012-02-15 22:00:51 +00001497 if (Captures.empty() && CaptureDefault == LCD_None)
1498 addFunctionPointerConversion(*this, IntroducerRange, Class,
1499 CallOperator);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001500
Douglas Gregor33e863c2012-02-15 22:08:38 +00001501 // Objective-C++:
1502 // The closure type for a lambda-expression has a public non-virtual
1503 // non-explicit const conversion function to a block pointer having the
1504 // same parameter and return types as the closure type's function call
1505 // operator.
Faisal Vali571df122013-09-29 08:45:24 +00001506 // FIXME: Fix generic lambda to block conversions.
1507 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1508 !Class->isGenericLambda())
Douglas Gregor33e863c2012-02-15 22:08:38 +00001509 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1510
Douglas Gregor04bbab52012-02-10 16:13:20 +00001511 // Finalize the lambda class.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001512 SmallVector<Decl*, 4> Fields;
1513 for (RecordDecl::field_iterator i = Class->field_begin(),
1514 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001515 Fields.push_back(*i);
Douglas Gregor04bbab52012-02-10 16:13:20 +00001516 ActOnFields(0, Class->getLocation(), Class, Fields,
1517 SourceLocation(), SourceLocation(), 0);
1518 CheckCompletedCXXClass(Class);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001519 }
1520
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001521 if (LambdaExprNeedsCleanups)
1522 ExprNeedsCleanups = true;
Douglas Gregor63798542012-02-20 19:44:39 +00001523
Douglas Gregor89625492012-02-09 08:14:43 +00001524 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettddd36ff2013-08-09 23:08:25 +00001525 CaptureDefault, CaptureDefaultLoc,
1526 Captures,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001527 ExplicitParams, ExplicitResultType,
1528 CaptureInits, ArrayIndexVars,
Richard Smith2589b9802012-07-25 03:56:55 +00001529 ArrayIndexStarts, Body->getLocEnd(),
1530 ContainsUnexpandedParameterPack);
David Majnemer9adc3612013-10-25 09:12:52 +00001531
Douglas Gregorb4328232012-02-14 00:00:48 +00001532 if (!CurContext->isDependentContext()) {
1533 switch (ExprEvalContexts.back().Context) {
David Majnemer9adc3612013-10-25 09:12:52 +00001534 // C++11 [expr.prim.lambda]p2:
1535 // A lambda-expression shall not appear in an unevaluated operand
1536 // (Clause 5).
Douglas Gregorb4328232012-02-14 00:00:48 +00001537 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +00001538 case UnevaluatedAbstract:
David Majnemer9adc3612013-10-25 09:12:52 +00001539 // C++1y [expr.const]p2:
1540 // A conditional-expression e is a core constant expression unless the
1541 // evaluation of e, following the rules of the abstract machine, would
1542 // evaluate [...] a lambda-expression.
David Majnemer2748da92013-11-05 08:01:18 +00001543 //
1544 // This is technically incorrect, there are some constant evaluated contexts
1545 // where this should be allowed. We should probably fix this when DR1607 is
1546 // ratified, it lays out the exact set of conditions where we shouldn't
1547 // allow a lambda-expression.
David Majnemer9adc3612013-10-25 09:12:52 +00001548 case ConstantEvaluated:
Douglas Gregorb4328232012-02-14 00:00:48 +00001549 // We don't actually diagnose this case immediately, because we
1550 // could be within a context where we might find out later that
1551 // the expression is potentially evaluated (e.g., for typeid).
1552 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1553 break;
Douglas Gregor89625492012-02-09 08:14:43 +00001554
Douglas Gregorb4328232012-02-14 00:00:48 +00001555 case PotentiallyEvaluated:
1556 case PotentiallyEvaluatedIfUsed:
1557 break;
1558 }
Douglas Gregor89625492012-02-09 08:14:43 +00001559 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001560
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001561 return MaybeBindToTemporary(Lambda);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001562}
Eli Friedman98b01ed2012-03-01 04:01:32 +00001563
1564ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1565 SourceLocation ConvLocation,
1566 CXXConversionDecl *Conv,
1567 Expr *Src) {
1568 // Make sure that the lambda call operator is marked used.
1569 CXXRecordDecl *Lambda = Conv->getParent();
1570 CXXMethodDecl *CallOperator
1571 = cast<CXXMethodDecl>(
David Blaikieff7d47a2012-12-19 00:45:41 +00001572 Lambda->lookup(
1573 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman98b01ed2012-03-01 04:01:32 +00001574 CallOperator->setReferenced();
Eli Friedman276dd182013-09-05 00:02:25 +00001575 CallOperator->markUsed(Context);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001576
1577 ExprResult Init = PerformCopyInitialization(
1578 InitializedEntity::InitializeBlock(ConvLocation,
1579 Src->getType(),
1580 /*NRVO=*/false),
1581 CurrentLocation, Src);
1582 if (!Init.isInvalid())
1583 Init = ActOnFinishFullExpr(Init.take());
1584
1585 if (Init.isInvalid())
1586 return ExprError();
1587
1588 // Create the new block to be returned.
1589 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1590
1591 // Set the type information.
1592 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1593 Block->setIsVariadic(CallOperator->isVariadic());
1594 Block->setBlockMissingReturnType(false);
1595
1596 // Add parameters.
1597 SmallVector<ParmVarDecl *, 4> BlockParams;
1598 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1599 ParmVarDecl *From = CallOperator->getParamDecl(I);
1600 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1601 From->getLocStart(),
1602 From->getLocation(),
1603 From->getIdentifier(),
1604 From->getType(),
1605 From->getTypeSourceInfo(),
1606 From->getStorageClass(),
Eli Friedman98b01ed2012-03-01 04:01:32 +00001607 /*DefaultArg=*/0));
1608 }
1609 Block->setParams(BlockParams);
1610
1611 Block->setIsConversionFromLambda(true);
1612
1613 // Add capture. The capture uses a fake variable, which doesn't correspond
1614 // to any actual memory location. However, the initializer copy-initializes
1615 // the lambda object.
1616 TypeSourceInfo *CapVarTSI =
1617 Context.getTrivialTypeSourceInfo(Src->getType());
1618 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1619 ConvLocation, 0,
1620 Src->getType(), CapVarTSI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001621 SC_None);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001622 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1623 /*Nested=*/false, /*Copy=*/Init.take());
1624 Block->setCaptures(Context, &Capture, &Capture + 1,
1625 /*CapturesCXXThis=*/false);
1626
1627 // Add a fake function body to the block. IR generation is responsible
1628 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramere2a929d2012-07-04 17:03:41 +00001629 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman98b01ed2012-03-01 04:01:32 +00001630
1631 // Create the block literal expression.
1632 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1633 ExprCleanupObjects.push_back(Block);
1634 ExprNeedsCleanups = true;
1635
1636 return BuildBlock;
1637}