• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- 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"
14 #include "clang/Sema/Initialization.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Sema/SemaInternal.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/AST/ExprCXX.h"
21 using namespace clang;
22 using namespace sema;
23 
createLambdaClosureType(SourceRange IntroducerRange,bool KnownDependent)24 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25                                              bool KnownDependent) {
26   DeclContext *DC = CurContext;
27   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
28     DC = DC->getParent();
29 
30   // Start constructing the lambda class.
31   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
32                                                      IntroducerRange.getBegin(),
33                                                      KnownDependent);
34   DC->addDecl(Class);
35 
36   return Class;
37 }
38 
39 /// \brief Determine whether the given context is or is enclosed in an inline
40 /// function.
isInInlineFunction(const DeclContext * DC)41 static bool isInInlineFunction(const DeclContext *DC) {
42   while (!DC->isFileContext()) {
43     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
44       if (FD->isInlined())
45         return true;
46 
47     DC = DC->getLexicalParent();
48   }
49 
50   return false;
51 }
52 
startLambdaDefinition(CXXRecordDecl * Class,SourceRange IntroducerRange,TypeSourceInfo * MethodType,SourceLocation EndLoc,llvm::ArrayRef<ParmVarDecl * > Params,llvm::Optional<unsigned> ManglingNumber,Decl * ContextDecl)53 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
54                  SourceRange IntroducerRange,
55                  TypeSourceInfo *MethodType,
56                  SourceLocation EndLoc,
57                  llvm::ArrayRef<ParmVarDecl *> Params,
58                  llvm::Optional<unsigned> ManglingNumber,
59                  Decl *ContextDecl) {
60   // C++11 [expr.prim.lambda]p5:
61   //   The closure type for a lambda-expression has a public inline function
62   //   call operator (13.5.4) whose parameters and return type are described by
63   //   the lambda-expression's parameter-declaration-clause and
64   //   trailing-return-type respectively.
65   DeclarationName MethodName
66     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67   DeclarationNameLoc MethodNameLoc;
68   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69     = IntroducerRange.getBegin().getRawEncoding();
70   MethodNameLoc.CXXOperatorName.EndOpNameLoc
71     = IntroducerRange.getEnd().getRawEncoding();
72   CXXMethodDecl *Method
73     = CXXMethodDecl::Create(Context, Class, EndLoc,
74                             DeclarationNameInfo(MethodName,
75                                                 IntroducerRange.getBegin(),
76                                                 MethodNameLoc),
77                             MethodType->getType(), MethodType,
78                             /*isStatic=*/false,
79                             SC_None,
80                             /*isInline=*/true,
81                             /*isConstExpr=*/false,
82                             EndLoc);
83   Method->setAccess(AS_public);
84 
85   // Temporarily set the lexical declaration context to the current
86   // context, so that the Scope stack matches the lexical nesting.
87   Method->setLexicalDeclContext(CurContext);
88 
89   // Add parameters.
90   if (!Params.empty()) {
91     Method->setParams(Params);
92     CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93                              const_cast<ParmVarDecl **>(Params.end()),
94                              /*CheckParameterNames=*/false);
95 
96     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97                                     PEnd = Method->param_end();
98          P != PEnd; ++P)
99       (*P)->setOwningFunction(Method);
100   }
101 
102   // If we don't already have a mangling number for this lambda expression,
103   // allocate one now.
104   if (!ManglingNumber) {
105     ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
106 
107     enum ContextKind {
108       Normal,
109       DefaultArgument,
110       DataMember,
111       StaticDataMember
112     } Kind = Normal;
113 
114     // Default arguments of member function parameters that appear in a class
115     // definition, as well as the initializers of data members, receive special
116     // treatment. Identify them.
117     if (ContextDecl) {
118       if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
119         if (const DeclContext *LexicalDC
120             = Param->getDeclContext()->getLexicalParent())
121           if (LexicalDC->isRecord())
122             Kind = DefaultArgument;
123       } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
124         if (Var->getDeclContext()->isRecord())
125           Kind = StaticDataMember;
126       } else if (isa<FieldDecl>(ContextDecl)) {
127         Kind = DataMember;
128       }
129     }
130 
131     switch (Kind) {
132       case Normal:
133         if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134           ManglingNumber = Context.getLambdaManglingNumber(Method);
135         else
136           ManglingNumber = 0;
137 
138         // There is no special context for this lambda.
139         ContextDecl = 0;
140         break;
141 
142       case StaticDataMember:
143         if (!CurContext->isDependentContext()) {
144           ManglingNumber = 0;
145           ContextDecl = 0;
146           break;
147         }
148         // Fall through to assign a mangling number.
149 
150       case DataMember:
151       case DefaultArgument:
152         ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153                            .getManglingNumber(Method);
154         break;
155     }
156   }
157 
158   Class->setLambdaMangling(*ManglingNumber, ContextDecl);
159   return Method;
160 }
161 
enterLambdaScope(CXXMethodDecl * CallOperator,SourceRange IntroducerRange,LambdaCaptureDefault CaptureDefault,bool ExplicitParams,bool ExplicitResultType,bool Mutable)162 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163                                         SourceRange IntroducerRange,
164                                         LambdaCaptureDefault CaptureDefault,
165                                         bool ExplicitParams,
166                                         bool ExplicitResultType,
167                                         bool Mutable) {
168   PushLambdaScope(CallOperator->getParent(), CallOperator);
169   LambdaScopeInfo *LSI = getCurLambda();
170   if (CaptureDefault == LCD_ByCopy)
171     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
172   else if (CaptureDefault == LCD_ByRef)
173     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
174   LSI->IntroducerRange = IntroducerRange;
175   LSI->ExplicitParams = ExplicitParams;
176   LSI->Mutable = Mutable;
177 
178   if (ExplicitResultType) {
179     LSI->ReturnType = CallOperator->getResultType();
180 
181     if (!LSI->ReturnType->isDependentType() &&
182         !LSI->ReturnType->isVoidType()) {
183       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184                               diag::err_lambda_incomplete_result)) {
185         // Do nothing.
186       } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187         Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
188           << LSI->ReturnType;
189       }
190     }
191   } else {
192     LSI->HasImplicitReturnType = true;
193   }
194 
195   return LSI;
196 }
197 
finishLambdaExplicitCaptures(LambdaScopeInfo * LSI)198 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199   LSI->finishedExplicitCaptures();
200 }
201 
addLambdaParameters(CXXMethodDecl * CallOperator,Scope * CurScope)202 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
203   // Introduce our parameters into the function scope
204   for (unsigned p = 0, NumParams = CallOperator->getNumParams();
205        p < NumParams; ++p) {
206     ParmVarDecl *Param = CallOperator->getParamDecl(p);
207 
208     // If this has an identifier, add it to the scope stack.
209     if (CurScope && Param->getIdentifier()) {
210       CheckShadow(CurScope, Param);
211 
212       PushOnScopeChains(Param, CurScope);
213     }
214   }
215 }
216 
ActOnStartOfLambdaDefinition(LambdaIntroducer & Intro,Declarator & ParamInfo,Scope * CurScope)217 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
218                                         Declarator &ParamInfo,
219                                         Scope *CurScope) {
220   // Determine if we're within a context where we know that the lambda will
221   // be dependent, because there are template parameters in scope.
222   bool KnownDependent = false;
223   if (Scope *TmplScope = CurScope->getTemplateParamParent())
224     if (!TmplScope->decl_empty())
225       KnownDependent = true;
226 
227   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
228 
229   // Determine the signature of the call operator.
230   TypeSourceInfo *MethodTyInfo;
231   bool ExplicitParams = true;
232   bool ExplicitResultType = true;
233   SourceLocation EndLoc;
234   llvm::ArrayRef<ParmVarDecl *> Params;
235   if (ParamInfo.getNumTypeObjects() == 0) {
236     // C++11 [expr.prim.lambda]p4:
237     //   If a lambda-expression does not include a lambda-declarator, it is as
238     //   if the lambda-declarator were ().
239     FunctionProtoType::ExtProtoInfo EPI;
240     EPI.HasTrailingReturn = true;
241     EPI.TypeQuals |= DeclSpec::TQ_const;
242     QualType MethodTy = Context.getFunctionType(Context.DependentTy,
243                                                 /*Args=*/0, /*NumArgs=*/0, EPI);
244     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
245     ExplicitParams = false;
246     ExplicitResultType = false;
247     EndLoc = Intro.Range.getEnd();
248   } else {
249     assert(ParamInfo.isFunctionDeclarator() &&
250            "lambda-declarator is a function");
251     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
252 
253     // C++11 [expr.prim.lambda]p5:
254     //   This function call operator is declared const (9.3.1) if and only if
255     //   the lambda-expression's parameter-declaration-clause is not followed
256     //   by mutable. It is neither virtual nor declared volatile. [...]
257     if (!FTI.hasMutableQualifier())
258       FTI.TypeQuals |= DeclSpec::TQ_const;
259 
260     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
261     assert(MethodTyInfo && "no type from lambda-declarator");
262     EndLoc = ParamInfo.getSourceRange().getEnd();
263 
264     ExplicitResultType
265       = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
266                                                         != Context.DependentTy;
267 
268     TypeLoc TL = MethodTyInfo->getTypeLoc();
269     FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
270     Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
271                                            Proto.getNumArgs());
272   }
273 
274   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
275                                                 MethodTyInfo, EndLoc, Params);
276 
277   if (ExplicitParams)
278     CheckCXXDefaultArguments(Method);
279 
280   // Attributes on the lambda apply to the method.
281   ProcessDeclAttributes(CurScope, Method, ParamInfo);
282 
283   // Introduce the function call operator as the current declaration context.
284   PushDeclContext(CurScope, Method);
285 
286   // Introduce the lambda scope.
287   LambdaScopeInfo *LSI
288     = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
289                        ExplicitResultType,
290                        (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
291 
292   // Handle explicit captures.
293   SourceLocation PrevCaptureLoc
294     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
295   for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
296          C = Intro.Captures.begin(),
297          E = Intro.Captures.end();
298        C != E;
299        PrevCaptureLoc = C->Loc, ++C) {
300     if (C->Kind == LCK_This) {
301       // C++11 [expr.prim.lambda]p8:
302       //   An identifier or this shall not appear more than once in a
303       //   lambda-capture.
304       if (LSI->isCXXThisCaptured()) {
305         Diag(C->Loc, diag::err_capture_more_than_once)
306           << "'this'"
307           << SourceRange(LSI->getCXXThisCapture().getLocation())
308           << FixItHint::CreateRemoval(
309                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
310         continue;
311       }
312 
313       // C++11 [expr.prim.lambda]p8:
314       //   If a lambda-capture includes a capture-default that is =, the
315       //   lambda-capture shall not contain this [...].
316       if (Intro.Default == LCD_ByCopy) {
317         Diag(C->Loc, diag::err_this_capture_with_copy_default)
318           << FixItHint::CreateRemoval(
319                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
320         continue;
321       }
322 
323       // C++11 [expr.prim.lambda]p12:
324       //   If this is captured by a local lambda expression, its nearest
325       //   enclosing function shall be a non-static member function.
326       QualType ThisCaptureType = getCurrentThisType();
327       if (ThisCaptureType.isNull()) {
328         Diag(C->Loc, diag::err_this_capture) << true;
329         continue;
330       }
331 
332       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
333       continue;
334     }
335 
336     assert(C->Id && "missing identifier for capture");
337 
338     // C++11 [expr.prim.lambda]p8:
339     //   If a lambda-capture includes a capture-default that is &, the
340     //   identifiers in the lambda-capture shall not be preceded by &.
341     //   If a lambda-capture includes a capture-default that is =, [...]
342     //   each identifier it contains shall be preceded by &.
343     if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
344       Diag(C->Loc, diag::err_reference_capture_with_reference_default)
345         << FixItHint::CreateRemoval(
346              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
347       continue;
348     } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
349       Diag(C->Loc, diag::err_copy_capture_with_copy_default)
350         << FixItHint::CreateRemoval(
351              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
352       continue;
353     }
354 
355     DeclarationNameInfo Name(C->Id, C->Loc);
356     LookupResult R(*this, Name, LookupOrdinaryName);
357     LookupName(R, CurScope);
358     if (R.isAmbiguous())
359       continue;
360     if (R.empty()) {
361       // FIXME: Disable corrections that would add qualification?
362       CXXScopeSpec ScopeSpec;
363       DeclFilterCCC<VarDecl> Validator;
364       if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
365         continue;
366     }
367 
368     // C++11 [expr.prim.lambda]p10:
369     //   The identifiers in a capture-list are looked up using the usual rules
370     //   for unqualified name lookup (3.4.1); each such lookup shall find a
371     //   variable with automatic storage duration declared in the reaching
372     //   scope of the local lambda expression.
373     //
374     // Note that the 'reaching scope' check happens in tryCaptureVariable().
375     VarDecl *Var = R.getAsSingle<VarDecl>();
376     if (!Var) {
377       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
378       continue;
379     }
380 
381     if (!Var->hasLocalStorage()) {
382       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
383       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
384       continue;
385     }
386 
387     // C++11 [expr.prim.lambda]p8:
388     //   An identifier or this shall not appear more than once in a
389     //   lambda-capture.
390     if (LSI->isCaptured(Var)) {
391       Diag(C->Loc, diag::err_capture_more_than_once)
392         << C->Id
393         << SourceRange(LSI->getCapture(Var).getLocation())
394         << FixItHint::CreateRemoval(
395              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
396       continue;
397     }
398 
399     // C++11 [expr.prim.lambda]p23:
400     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
401     SourceLocation EllipsisLoc;
402     if (C->EllipsisLoc.isValid()) {
403       if (Var->isParameterPack()) {
404         EllipsisLoc = C->EllipsisLoc;
405       } else {
406         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
407           << SourceRange(C->Loc);
408 
409         // Just ignore the ellipsis.
410       }
411     } else if (Var->isParameterPack()) {
412       Diag(C->Loc, diag::err_lambda_unexpanded_pack);
413       continue;
414     }
415 
416     TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
417                                                  TryCapture_ExplicitByVal;
418     tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
419   }
420   finishLambdaExplicitCaptures(LSI);
421 
422   // Add lambda parameters into scope.
423   addLambdaParameters(Method, CurScope);
424 
425   // Enter a new evaluation context to insulate the lambda from any
426   // cleanups from the enclosing full-expression.
427   PushExpressionEvaluationContext(PotentiallyEvaluated);
428 }
429 
ActOnLambdaError(SourceLocation StartLoc,Scope * CurScope,bool IsInstantiation)430 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
431                             bool IsInstantiation) {
432   // Leave the expression-evaluation context.
433   DiscardCleanupsInEvaluationContext();
434   PopExpressionEvaluationContext();
435 
436   // Leave the context of the lambda.
437   if (!IsInstantiation)
438     PopDeclContext();
439 
440   // Finalize the lambda.
441   LambdaScopeInfo *LSI = getCurLambda();
442   CXXRecordDecl *Class = LSI->Lambda;
443   Class->setInvalidDecl();
444   SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
445   ActOnFields(0, Class->getLocation(), Class, Fields,
446               SourceLocation(), SourceLocation(), 0);
447   CheckCompletedCXXClass(Class);
448 
449   PopFunctionScopeInfo();
450 }
451 
452 /// \brief Add a lambda's conversion to function pointer, as described in
453 /// C++11 [expr.prim.lambda]p6.
addFunctionPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)454 static void addFunctionPointerConversion(Sema &S,
455                                          SourceRange IntroducerRange,
456                                          CXXRecordDecl *Class,
457                                          CXXMethodDecl *CallOperator) {
458   // Add the conversion to function pointer.
459   const FunctionProtoType *Proto
460     = CallOperator->getType()->getAs<FunctionProtoType>();
461   QualType FunctionPtrTy;
462   QualType FunctionTy;
463   {
464     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
465     ExtInfo.TypeQuals = 0;
466     FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
467                                            Proto->arg_type_begin(),
468                                            Proto->getNumArgs(),
469                                            ExtInfo);
470     FunctionPtrTy = S.Context.getPointerType(FunctionTy);
471   }
472 
473   FunctionProtoType::ExtProtoInfo ExtInfo;
474   ExtInfo.TypeQuals = Qualifiers::Const;
475   QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
476 
477   SourceLocation Loc = IntroducerRange.getBegin();
478   DeclarationName Name
479     = S.Context.DeclarationNames.getCXXConversionFunctionName(
480         S.Context.getCanonicalType(FunctionPtrTy));
481   DeclarationNameLoc NameLoc;
482   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
483                                                                Loc);
484   CXXConversionDecl *Conversion
485     = CXXConversionDecl::Create(S.Context, Class, Loc,
486                                 DeclarationNameInfo(Name, Loc, NameLoc),
487                                 ConvTy,
488                                 S.Context.getTrivialTypeSourceInfo(ConvTy,
489                                                                    Loc),
490                                 /*isInline=*/false, /*isExplicit=*/false,
491                                 /*isConstexpr=*/false,
492                                 CallOperator->getBody()->getLocEnd());
493   Conversion->setAccess(AS_public);
494   Conversion->setImplicit(true);
495   Class->addDecl(Conversion);
496 
497   // Add a non-static member function "__invoke" that will be the result of
498   // the conversion.
499   Name = &S.Context.Idents.get("__invoke");
500   CXXMethodDecl *Invoke
501     = CXXMethodDecl::Create(S.Context, Class, Loc,
502                             DeclarationNameInfo(Name, Loc), FunctionTy,
503                             CallOperator->getTypeSourceInfo(),
504                             /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
505                             /*IsConstexpr=*/false,
506                             CallOperator->getBody()->getLocEnd());
507   SmallVector<ParmVarDecl *, 4> InvokeParams;
508   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
509     ParmVarDecl *From = CallOperator->getParamDecl(I);
510     InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
511                                                From->getLocStart(),
512                                                From->getLocation(),
513                                                From->getIdentifier(),
514                                                From->getType(),
515                                                From->getTypeSourceInfo(),
516                                                From->getStorageClass(),
517                                                From->getStorageClassAsWritten(),
518                                                /*DefaultArg=*/0));
519   }
520   Invoke->setParams(InvokeParams);
521   Invoke->setAccess(AS_private);
522   Invoke->setImplicit(true);
523   Class->addDecl(Invoke);
524 }
525 
526 /// \brief Add a lambda's conversion to block pointer.
addBlockPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)527 static void addBlockPointerConversion(Sema &S,
528                                       SourceRange IntroducerRange,
529                                       CXXRecordDecl *Class,
530                                       CXXMethodDecl *CallOperator) {
531   const FunctionProtoType *Proto
532     = CallOperator->getType()->getAs<FunctionProtoType>();
533   QualType BlockPtrTy;
534   {
535     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
536     ExtInfo.TypeQuals = 0;
537     QualType FunctionTy
538       = S.Context.getFunctionType(Proto->getResultType(),
539                                   Proto->arg_type_begin(),
540                                   Proto->getNumArgs(),
541                                   ExtInfo);
542     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
543   }
544 
545   FunctionProtoType::ExtProtoInfo ExtInfo;
546   ExtInfo.TypeQuals = Qualifiers::Const;
547   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
548 
549   SourceLocation Loc = IntroducerRange.getBegin();
550   DeclarationName Name
551     = S.Context.DeclarationNames.getCXXConversionFunctionName(
552         S.Context.getCanonicalType(BlockPtrTy));
553   DeclarationNameLoc NameLoc;
554   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
555   CXXConversionDecl *Conversion
556     = CXXConversionDecl::Create(S.Context, Class, Loc,
557                                 DeclarationNameInfo(Name, Loc, NameLoc),
558                                 ConvTy,
559                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
560                                 /*isInline=*/false, /*isExplicit=*/false,
561                                 /*isConstexpr=*/false,
562                                 CallOperator->getBody()->getLocEnd());
563   Conversion->setAccess(AS_public);
564   Conversion->setImplicit(true);
565   Class->addDecl(Conversion);
566 }
567 
ActOnLambdaExpr(SourceLocation StartLoc,Stmt * Body,Scope * CurScope,bool IsInstantiation)568 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
569                                  Scope *CurScope,
570                                  bool IsInstantiation) {
571   // Collect information from the lambda scope.
572   llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
573   llvm::SmallVector<Expr *, 4> CaptureInits;
574   LambdaCaptureDefault CaptureDefault;
575   CXXRecordDecl *Class;
576   CXXMethodDecl *CallOperator;
577   SourceRange IntroducerRange;
578   bool ExplicitParams;
579   bool ExplicitResultType;
580   bool LambdaExprNeedsCleanups;
581   llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
582   llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
583   {
584     LambdaScopeInfo *LSI = getCurLambda();
585     CallOperator = LSI->CallOperator;
586     Class = LSI->Lambda;
587     IntroducerRange = LSI->IntroducerRange;
588     ExplicitParams = LSI->ExplicitParams;
589     ExplicitResultType = !LSI->HasImplicitReturnType;
590     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
591     ArrayIndexVars.swap(LSI->ArrayIndexVars);
592     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
593 
594     // Translate captures.
595     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
596       LambdaScopeInfo::Capture From = LSI->Captures[I];
597       assert(!From.isBlockCapture() && "Cannot capture __block variables");
598       bool IsImplicit = I >= LSI->NumExplicitCaptures;
599 
600       // Handle 'this' capture.
601       if (From.isThisCapture()) {
602         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
603                                                IsImplicit,
604                                                LCK_This));
605         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
606                                                          getCurrentThisType(),
607                                                          /*isImplicit=*/true));
608         continue;
609       }
610 
611       VarDecl *Var = From.getVariable();
612       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
613       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
614                                              Kind, Var, From.getEllipsisLoc()));
615       CaptureInits.push_back(From.getCopyExpr());
616     }
617 
618     switch (LSI->ImpCaptureStyle) {
619     case CapturingScopeInfo::ImpCap_None:
620       CaptureDefault = LCD_None;
621       break;
622 
623     case CapturingScopeInfo::ImpCap_LambdaByval:
624       CaptureDefault = LCD_ByCopy;
625       break;
626 
627     case CapturingScopeInfo::ImpCap_LambdaByref:
628       CaptureDefault = LCD_ByRef;
629       break;
630 
631     case CapturingScopeInfo::ImpCap_Block:
632       llvm_unreachable("block capture in lambda");
633       break;
634     }
635 
636     // C++11 [expr.prim.lambda]p4:
637     //   If a lambda-expression does not include a
638     //   trailing-return-type, it is as if the trailing-return-type
639     //   denotes the following type:
640     // FIXME: Assumes current resolution to core issue 975.
641     if (LSI->HasImplicitReturnType) {
642       //   - if there are no return statements in the
643       //     compound-statement, or all return statements return
644       //     either an expression of type void or no expression or
645       //     braced-init-list, the type void;
646       if (LSI->ReturnType.isNull()) {
647         LSI->ReturnType = Context.VoidTy;
648       } else {
649         // C++11 [expr.prim.lambda]p4:
650         //   - if the compound-statement is of the form
651         //
652         //       { attribute-specifier-seq[opt] return expression ; }
653         //
654         //     the type of the returned expression after
655         //     lvalue-to-rvalue conversion (4.1), array-to-pointer
656         //     conver- sion (4.2), and function-to-pointer conversion
657         //     (4.3);
658         //
659         // Since we're accepting the resolution to a post-C++11 core
660         // issue with a non-trivial extension, provide a warning (by
661         // default).
662         CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
663         if (!(CompoundBody->size() == 1 &&
664               isa<ReturnStmt>(*CompoundBody->body_begin())) &&
665             !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
666           Diag(IntroducerRange.getBegin(),
667                diag::ext_lambda_implies_void_return);
668       }
669 
670       // Create a function type with the inferred return type.
671       const FunctionProtoType *Proto
672         = CallOperator->getType()->getAs<FunctionProtoType>();
673       QualType FunctionTy
674         = Context.getFunctionType(LSI->ReturnType,
675                                   Proto->arg_type_begin(),
676                                   Proto->getNumArgs(),
677                                   Proto->getExtProtoInfo());
678       CallOperator->setType(FunctionTy);
679     }
680 
681     // C++ [expr.prim.lambda]p7:
682     //   The lambda-expression's compound-statement yields the
683     //   function-body (8.4) of the function call operator [...].
684     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
685     CallOperator->setLexicalDeclContext(Class);
686     Class->addDecl(CallOperator);
687     PopExpressionEvaluationContext();
688 
689     // C++11 [expr.prim.lambda]p6:
690     //   The closure type for a lambda-expression with no lambda-capture
691     //   has a public non-virtual non-explicit const conversion function
692     //   to pointer to function having the same parameter and return
693     //   types as the closure type's function call operator.
694     if (Captures.empty() && CaptureDefault == LCD_None)
695       addFunctionPointerConversion(*this, IntroducerRange, Class,
696                                    CallOperator);
697 
698     // Objective-C++:
699     //   The closure type for a lambda-expression has a public non-virtual
700     //   non-explicit const conversion function to a block pointer having the
701     //   same parameter and return types as the closure type's function call
702     //   operator.
703     if (getLangOpts().Blocks && getLangOpts().ObjC1)
704       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
705 
706     // Finalize the lambda class.
707     SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
708     ActOnFields(0, Class->getLocation(), Class, Fields,
709                 SourceLocation(), SourceLocation(), 0);
710     CheckCompletedCXXClass(Class);
711   }
712 
713   if (LambdaExprNeedsCleanups)
714     ExprNeedsCleanups = true;
715 
716   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
717                                           CaptureDefault, Captures,
718                                           ExplicitParams, ExplicitResultType,
719                                           CaptureInits, ArrayIndexVars,
720                                           ArrayIndexStarts, Body->getLocEnd());
721 
722   // C++11 [expr.prim.lambda]p2:
723   //   A lambda-expression shall not appear in an unevaluated operand
724   //   (Clause 5).
725   if (!CurContext->isDependentContext()) {
726     switch (ExprEvalContexts.back().Context) {
727     case Unevaluated:
728       // We don't actually diagnose this case immediately, because we
729       // could be within a context where we might find out later that
730       // the expression is potentially evaluated (e.g., for typeid).
731       ExprEvalContexts.back().Lambdas.push_back(Lambda);
732       break;
733 
734     case ConstantEvaluated:
735     case PotentiallyEvaluated:
736     case PotentiallyEvaluatedIfUsed:
737       break;
738     }
739   }
740 
741   return MaybeBindToTemporary(Lambda);
742 }
743 
BuildBlockForLambdaConversion(SourceLocation CurrentLocation,SourceLocation ConvLocation,CXXConversionDecl * Conv,Expr * Src)744 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
745                                                SourceLocation ConvLocation,
746                                                CXXConversionDecl *Conv,
747                                                Expr *Src) {
748   // Make sure that the lambda call operator is marked used.
749   CXXRecordDecl *Lambda = Conv->getParent();
750   CXXMethodDecl *CallOperator
751     = cast<CXXMethodDecl>(
752         *Lambda->lookup(
753           Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
754   CallOperator->setReferenced();
755   CallOperator->setUsed();
756 
757   ExprResult Init = PerformCopyInitialization(
758                       InitializedEntity::InitializeBlock(ConvLocation,
759                                                          Src->getType(),
760                                                          /*NRVO=*/false),
761                       CurrentLocation, Src);
762   if (!Init.isInvalid())
763     Init = ActOnFinishFullExpr(Init.take());
764 
765   if (Init.isInvalid())
766     return ExprError();
767 
768   // Create the new block to be returned.
769   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
770 
771   // Set the type information.
772   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
773   Block->setIsVariadic(CallOperator->isVariadic());
774   Block->setBlockMissingReturnType(false);
775 
776   // Add parameters.
777   SmallVector<ParmVarDecl *, 4> BlockParams;
778   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
779     ParmVarDecl *From = CallOperator->getParamDecl(I);
780     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
781                                               From->getLocStart(),
782                                               From->getLocation(),
783                                               From->getIdentifier(),
784                                               From->getType(),
785                                               From->getTypeSourceInfo(),
786                                               From->getStorageClass(),
787                                             From->getStorageClassAsWritten(),
788                                               /*DefaultArg=*/0));
789   }
790   Block->setParams(BlockParams);
791 
792   Block->setIsConversionFromLambda(true);
793 
794   // Add capture. The capture uses a fake variable, which doesn't correspond
795   // to any actual memory location. However, the initializer copy-initializes
796   // the lambda object.
797   TypeSourceInfo *CapVarTSI =
798       Context.getTrivialTypeSourceInfo(Src->getType());
799   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
800                                     ConvLocation, 0,
801                                     Src->getType(), CapVarTSI,
802                                     SC_None, SC_None);
803   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
804                              /*Nested=*/false, /*Copy=*/Init.take());
805   Block->setCaptures(Context, &Capture, &Capture + 1,
806                      /*CapturesCXXThis=*/false);
807 
808   // Add a fake function body to the block. IR generation is responsible
809   // for filling in the actual body, which cannot be expressed as an AST.
810   Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
811                                             ConvLocation,
812                                             ConvLocation));
813 
814   // Create the block literal expression.
815   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
816   ExprCleanupObjects.push_back(Block);
817   ExprNeedsCleanups = true;
818 
819   return BuildBlock;
820 }
821