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/AST/ASTLambda.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/ScopeInfo.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "TypeLocBuilder.h"
24 using namespace clang;
25 using namespace sema;
26 
27 
28 static inline TemplateParameterList *
29 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
30   if (LSI->GLTemplateParameterList)
31     return LSI->GLTemplateParameterList;
32 
33   if (LSI->AutoTemplateParams.size()) {
34     SourceRange IntroRange = LSI->IntroducerRange;
35     SourceLocation LAngleLoc = IntroRange.getBegin();
36     SourceLocation RAngleLoc = IntroRange.getEnd();
37     LSI->GLTemplateParameterList = TemplateParameterList::Create(
38                                    SemaRef.Context,
39                                    /*Template kw loc*/SourceLocation(),
40                                    LAngleLoc,
41                                    (NamedDecl**)LSI->AutoTemplateParams.data(),
42                                    LSI->AutoTemplateParams.size(), RAngleLoc);
43   }
44   return LSI->GLTemplateParameterList;
45 }
46 
47 
48 
49 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
50                                              TypeSourceInfo *Info,
51                                              bool KnownDependent,
52                                              LambdaCaptureDefault CaptureDefault) {
53   DeclContext *DC = CurContext;
54   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
55     DC = DC->getParent();
56   bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
57                                                                *this);
58   // Start constructing the lambda class.
59   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
60                                                      IntroducerRange.getBegin(),
61                                                      KnownDependent,
62                                                      IsGenericLambda,
63                                                      CaptureDefault);
64   DC->addDecl(Class);
65 
66   return Class;
67 }
68 
69 /// \brief Determine whether the given context is or is enclosed in an inline
70 /// function.
71 static bool isInInlineFunction(const DeclContext *DC) {
72   while (!DC->isFileContext()) {
73     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
74       if (FD->isInlined())
75         return true;
76 
77     DC = DC->getLexicalParent();
78   }
79 
80   return false;
81 }
82 
83 MangleNumberingContext *
84 Sema::getCurrentMangleNumberContext(const DeclContext *DC,
85                                     Decl *&ManglingContextDecl) {
86   // Compute the context for allocating mangling numbers in the current
87   // expression, if the ABI requires them.
88   ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
89 
90   enum ContextKind {
91     Normal,
92     DefaultArgument,
93     DataMember,
94     StaticDataMember
95   } Kind = Normal;
96 
97   // Default arguments of member function parameters that appear in a class
98   // definition, as well as the initializers of data members, receive special
99   // treatment. Identify them.
100   if (ManglingContextDecl) {
101     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
102       if (const DeclContext *LexicalDC
103           = Param->getDeclContext()->getLexicalParent())
104         if (LexicalDC->isRecord())
105           Kind = DefaultArgument;
106     } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
107       if (Var->getDeclContext()->isRecord())
108         Kind = StaticDataMember;
109     } else if (isa<FieldDecl>(ManglingContextDecl)) {
110       Kind = DataMember;
111     }
112   }
113 
114   // Itanium ABI [5.1.7]:
115   //   In the following contexts [...] the one-definition rule requires closure
116   //   types in different translation units to "correspond":
117   bool IsInNonspecializedTemplate =
118     !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
119   switch (Kind) {
120   case Normal:
121     //  -- the bodies of non-exported nonspecialized template functions
122     //  -- the bodies of inline functions
123     if ((IsInNonspecializedTemplate &&
124          !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
125         isInInlineFunction(CurContext)) {
126       ManglingContextDecl = 0;
127       return &Context.getManglingNumberContext(DC);
128     }
129 
130     ManglingContextDecl = 0;
131     return 0;
132 
133   case StaticDataMember:
134     //  -- the initializers of nonspecialized static members of template classes
135     if (!IsInNonspecializedTemplate) {
136       ManglingContextDecl = 0;
137       return 0;
138     }
139     // Fall through to get the current context.
140 
141   case DataMember:
142     //  -- the in-class initializers of class members
143   case DefaultArgument:
144     //  -- default arguments appearing in class definitions
145     return &ExprEvalContexts.back().getMangleNumberingContext(Context);
146   }
147 
148   llvm_unreachable("unexpected context");
149 }
150 
151 MangleNumberingContext &
152 Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
153     ASTContext &Ctx) {
154   assert(ManglingContextDecl && "Need to have a context declaration");
155   if (!MangleNumbering)
156     MangleNumbering = Ctx.createMangleNumberingContext();
157   return *MangleNumbering;
158 }
159 
160 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
161                                            SourceRange IntroducerRange,
162                                            TypeSourceInfo *MethodTypeInfo,
163                                            SourceLocation EndLoc,
164                                            ArrayRef<ParmVarDecl *> Params) {
165   QualType MethodType = MethodTypeInfo->getType();
166   TemplateParameterList *TemplateParams =
167             getGenericLambdaTemplateParameterList(getCurLambda(), *this);
168   // If a lambda appears in a dependent context or is a generic lambda (has
169   // template parameters) and has an 'auto' return type, deduce it to a
170   // dependent type.
171   if (Class->isDependentContext() || TemplateParams) {
172     const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
173     QualType Result = FPT->getResultType();
174     if (Result->isUndeducedType()) {
175       Result = SubstAutoType(Result, Context.DependentTy);
176       MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
177                                            FPT->getExtProtoInfo());
178     }
179   }
180 
181   // C++11 [expr.prim.lambda]p5:
182   //   The closure type for a lambda-expression has a public inline function
183   //   call operator (13.5.4) whose parameters and return type are described by
184   //   the lambda-expression's parameter-declaration-clause and
185   //   trailing-return-type respectively.
186   DeclarationName MethodName
187     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
188   DeclarationNameLoc MethodNameLoc;
189   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
190     = IntroducerRange.getBegin().getRawEncoding();
191   MethodNameLoc.CXXOperatorName.EndOpNameLoc
192     = IntroducerRange.getEnd().getRawEncoding();
193   CXXMethodDecl *Method
194     = CXXMethodDecl::Create(Context, Class, EndLoc,
195                             DeclarationNameInfo(MethodName,
196                                                 IntroducerRange.getBegin(),
197                                                 MethodNameLoc),
198                             MethodType, MethodTypeInfo,
199                             SC_None,
200                             /*isInline=*/true,
201                             /*isConstExpr=*/false,
202                             EndLoc);
203   Method->setAccess(AS_public);
204 
205   // Temporarily set the lexical declaration context to the current
206   // context, so that the Scope stack matches the lexical nesting.
207   Method->setLexicalDeclContext(CurContext);
208   // Create a function template if we have a template parameter list
209   FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
210             FunctionTemplateDecl::Create(Context, Class,
211                                          Method->getLocation(), MethodName,
212                                          TemplateParams,
213                                          Method) : 0;
214   if (TemplateMethod) {
215     TemplateMethod->setLexicalDeclContext(CurContext);
216     TemplateMethod->setAccess(AS_public);
217     Method->setDescribedFunctionTemplate(TemplateMethod);
218   }
219 
220   // Add parameters.
221   if (!Params.empty()) {
222     Method->setParams(Params);
223     CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
224                              const_cast<ParmVarDecl **>(Params.end()),
225                              /*CheckParameterNames=*/false);
226 
227     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
228                                     PEnd = Method->param_end();
229          P != PEnd; ++P)
230       (*P)->setOwningFunction(Method);
231   }
232 
233   Decl *ManglingContextDecl;
234   if (MangleNumberingContext *MCtx =
235           getCurrentMangleNumberContext(Class->getDeclContext(),
236                                         ManglingContextDecl)) {
237     unsigned ManglingNumber = MCtx->getManglingNumber(Method);
238     Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
239   }
240 
241   return Method;
242 }
243 
244 void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
245                                         CXXMethodDecl *CallOperator,
246                                         SourceRange IntroducerRange,
247                                         LambdaCaptureDefault CaptureDefault,
248                                         SourceLocation CaptureDefaultLoc,
249                                         bool ExplicitParams,
250                                         bool ExplicitResultType,
251                                         bool Mutable) {
252   LSI->CallOperator = CallOperator;
253   CXXRecordDecl *LambdaClass = CallOperator->getParent();
254   LSI->Lambda = LambdaClass;
255   if (CaptureDefault == LCD_ByCopy)
256     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
257   else if (CaptureDefault == LCD_ByRef)
258     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
259   LSI->CaptureDefaultLoc = CaptureDefaultLoc;
260   LSI->IntroducerRange = IntroducerRange;
261   LSI->ExplicitParams = ExplicitParams;
262   LSI->Mutable = Mutable;
263 
264   if (ExplicitResultType) {
265     LSI->ReturnType = CallOperator->getResultType();
266 
267     if (!LSI->ReturnType->isDependentType() &&
268         !LSI->ReturnType->isVoidType()) {
269       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
270                               diag::err_lambda_incomplete_result)) {
271         // Do nothing.
272       }
273     }
274   } else {
275     LSI->HasImplicitReturnType = true;
276   }
277 }
278 
279 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
280   LSI->finishedExplicitCaptures();
281 }
282 
283 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
284   // Introduce our parameters into the function scope
285   for (unsigned p = 0, NumParams = CallOperator->getNumParams();
286        p < NumParams; ++p) {
287     ParmVarDecl *Param = CallOperator->getParamDecl(p);
288 
289     // If this has an identifier, add it to the scope stack.
290     if (CurScope && Param->getIdentifier()) {
291       CheckShadow(CurScope, Param);
292 
293       PushOnScopeChains(Param, CurScope);
294     }
295   }
296 }
297 
298 /// If this expression is an enumerator-like expression of some type
299 /// T, return the type T; otherwise, return null.
300 ///
301 /// Pointer comparisons on the result here should always work because
302 /// it's derived from either the parent of an EnumConstantDecl
303 /// (i.e. the definition) or the declaration returned by
304 /// EnumType::getDecl() (i.e. the definition).
305 static EnumDecl *findEnumForBlockReturn(Expr *E) {
306   // An expression is an enumerator-like expression of type T if,
307   // ignoring parens and parens-like expressions:
308   E = E->IgnoreParens();
309 
310   //  - it is an enumerator whose enum type is T or
311   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
312     if (EnumConstantDecl *D
313           = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
314       return cast<EnumDecl>(D->getDeclContext());
315     }
316     return 0;
317   }
318 
319   //  - it is a comma expression whose RHS is an enumerator-like
320   //    expression of type T or
321   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
322     if (BO->getOpcode() == BO_Comma)
323       return findEnumForBlockReturn(BO->getRHS());
324     return 0;
325   }
326 
327   //  - it is a statement-expression whose value expression is an
328   //    enumerator-like expression of type T or
329   if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
330     if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
331       return findEnumForBlockReturn(last);
332     return 0;
333   }
334 
335   //   - it is a ternary conditional operator (not the GNU ?:
336   //     extension) whose second and third operands are
337   //     enumerator-like expressions of type T or
338   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
339     if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
340       if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
341         return ED;
342     return 0;
343   }
344 
345   // (implicitly:)
346   //   - it is an implicit integral conversion applied to an
347   //     enumerator-like expression of type T or
348   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
349     // We can sometimes see integral conversions in valid
350     // enumerator-like expressions.
351     if (ICE->getCastKind() == CK_IntegralCast)
352       return findEnumForBlockReturn(ICE->getSubExpr());
353 
354     // Otherwise, just rely on the type.
355   }
356 
357   //   - it is an expression of that formal enum type.
358   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
359     return ET->getDecl();
360   }
361 
362   // Otherwise, nope.
363   return 0;
364 }
365 
366 /// Attempt to find a type T for which the returned expression of the
367 /// given statement is an enumerator-like expression of that type.
368 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
369   if (Expr *retValue = ret->getRetValue())
370     return findEnumForBlockReturn(retValue);
371   return 0;
372 }
373 
374 /// Attempt to find a common type T for which all of the returned
375 /// expressions in a block are enumerator-like expressions of that
376 /// type.
377 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
378   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
379 
380   // Try to find one for the first return.
381   EnumDecl *ED = findEnumForBlockReturn(*i);
382   if (!ED) return 0;
383 
384   // Check that the rest of the returns have the same enum.
385   for (++i; i != e; ++i) {
386     if (findEnumForBlockReturn(*i) != ED)
387       return 0;
388   }
389 
390   // Never infer an anonymous enum type.
391   if (!ED->hasNameForLinkage()) return 0;
392 
393   return ED;
394 }
395 
396 /// Adjust the given return statements so that they formally return
397 /// the given type.  It should require, at most, an IntegralCast.
398 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
399                                      QualType returnType) {
400   for (ArrayRef<ReturnStmt*>::iterator
401          i = returns.begin(), e = returns.end(); i != e; ++i) {
402     ReturnStmt *ret = *i;
403     Expr *retValue = ret->getRetValue();
404     if (S.Context.hasSameType(retValue->getType(), returnType))
405       continue;
406 
407     // Right now we only support integral fixup casts.
408     assert(returnType->isIntegralOrUnscopedEnumerationType());
409     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
410 
411     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
412 
413     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
414     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
415                                  E, /*base path*/ 0, VK_RValue);
416     if (cleanups) {
417       cleanups->setSubExpr(E);
418     } else {
419       ret->setRetValue(E);
420     }
421   }
422 }
423 
424 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
425   assert(CSI.HasImplicitReturnType);
426   // If it was ever a placeholder, it had to been deduced to DependentTy.
427   assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
428 
429   // C++ Core Issue #975, proposed resolution:
430   //   If a lambda-expression does not include a trailing-return-type,
431   //   it is as if the trailing-return-type denotes the following type:
432   //     - if there are no return statements in the compound-statement,
433   //       or all return statements return either an expression of type
434   //       void or no expression or braced-init-list, the type void;
435   //     - otherwise, if all return statements return an expression
436   //       and the types of the returned expressions after
437   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
438   //       array-to-pointer conversion (4.2 [conv.array]), and
439   //       function-to-pointer conversion (4.3 [conv.func]) are the
440   //       same, that common type;
441   //     - otherwise, the program is ill-formed.
442   //
443   // In addition, in blocks in non-C++ modes, if all of the return
444   // statements are enumerator-like expressions of some type T, where
445   // T has a name for linkage, then we infer the return type of the
446   // block to be that type.
447 
448   // First case: no return statements, implicit void return type.
449   ASTContext &Ctx = getASTContext();
450   if (CSI.Returns.empty()) {
451     // It's possible there were simply no /valid/ return statements.
452     // In this case, the first one we found may have at least given us a type.
453     if (CSI.ReturnType.isNull())
454       CSI.ReturnType = Ctx.VoidTy;
455     return;
456   }
457 
458   // Second case: at least one return statement has dependent type.
459   // Delay type checking until instantiation.
460   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
461   if (CSI.ReturnType->isDependentType())
462     return;
463 
464   // Try to apply the enum-fuzz rule.
465   if (!getLangOpts().CPlusPlus) {
466     assert(isa<BlockScopeInfo>(CSI));
467     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
468     if (ED) {
469       CSI.ReturnType = Context.getTypeDeclType(ED);
470       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
471       return;
472     }
473   }
474 
475   // Third case: only one return statement. Don't bother doing extra work!
476   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
477                                          E = CSI.Returns.end();
478   if (I+1 == E)
479     return;
480 
481   // General case: many return statements.
482   // Check that they all have compatible return types.
483 
484   // We require the return types to strictly match here.
485   // Note that we've already done the required promotions as part of
486   // processing the return statement.
487   for (; I != E; ++I) {
488     const ReturnStmt *RS = *I;
489     const Expr *RetE = RS->getRetValue();
490 
491     QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
492     if (Context.hasSameType(ReturnType, CSI.ReturnType))
493       continue;
494 
495     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
496     // TODO: It's possible that the *first* return is the divergent one.
497     Diag(RS->getLocStart(),
498          diag::err_typecheck_missing_return_type_incompatible)
499       << ReturnType << CSI.ReturnType
500       << isa<LambdaScopeInfo>(CSI);
501     // Continue iterating so that we keep emitting diagnostics.
502   }
503 }
504 
505 VarDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
506                                 IdentifierInfo *Id, Expr *Init) {
507   // C++1y [expr.prim.lambda]p11:
508   //   An init-capture behaves as if it declares and explicitly captures
509   //   a variable of the form
510   //     "auto init-capture;"
511   QualType DeductType = Context.getAutoDeductType();
512   TypeLocBuilder TLB;
513   TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
514   if (ByRef) {
515     DeductType = BuildReferenceType(DeductType, true, Loc, Id);
516     assert(!DeductType.isNull() && "can't build reference to auto");
517     TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
518   }
519   TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
520 
521   // Create a dummy variable representing the init-capture. This is not actually
522   // used as a variable, and only exists as a way to name and refer to the
523   // init-capture.
524   // FIXME: Pass in separate source locations for '&' and identifier.
525   VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
526                                    Loc, Id, TSI->getType(), TSI, SC_Auto);
527   NewVD->setInitCapture(true);
528   NewVD->setReferenced(true);
529   NewVD->markUsed(Context);
530 
531   // We do not need to distinguish between direct-list-initialization
532   // and copy-list-initialization here, because we will always deduce
533   // std::initializer_list<T>, and direct- and copy-list-initialization
534   // always behave the same for such a type.
535   // FIXME: We should model whether an '=' was present.
536   bool DirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
537   AddInitializerToDecl(NewVD, Init, DirectInit, /*ContainsAuto*/true);
538   return NewVD;
539 }
540 
541 FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
542   FieldDecl *Field = FieldDecl::Create(
543       Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
544       0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
545   Field->setImplicit(true);
546   Field->setAccess(AS_private);
547   LSI->Lambda->addDecl(Field);
548 
549   LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
550                   /*isNested*/false, Var->getLocation(), SourceLocation(),
551                   Var->getType(), Var->getInit());
552   return Field;
553 }
554 
555 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
556                   Declarator &ParamInfo, Scope *CurScope) {
557   // Determine if we're within a context where we know that the lambda will
558   // be dependent, because there are template parameters in scope.
559   bool KnownDependent = false;
560   LambdaScopeInfo *const LSI = getCurLambda();
561   assert(LSI && "LambdaScopeInfo should be on stack!");
562   TemplateParameterList *TemplateParams =
563             getGenericLambdaTemplateParameterList(LSI, *this);
564 
565   if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
566     // Since we have our own TemplateParams, so check if an outer scope
567     // has template params, only then are we in a dependent scope.
568     if (TemplateParams)  {
569       TmplScope = TmplScope->getParent();
570       TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
571     }
572     if (TmplScope && !TmplScope->decl_empty())
573       KnownDependent = true;
574   }
575   // Determine the signature of the call operator.
576   TypeSourceInfo *MethodTyInfo;
577   bool ExplicitParams = true;
578   bool ExplicitResultType = true;
579   bool ContainsUnexpandedParameterPack = false;
580   SourceLocation EndLoc;
581   SmallVector<ParmVarDecl *, 8> Params;
582   if (ParamInfo.getNumTypeObjects() == 0) {
583     // C++11 [expr.prim.lambda]p4:
584     //   If a lambda-expression does not include a lambda-declarator, it is as
585     //   if the lambda-declarator were ().
586     FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
587         /*IsVariadic=*/false, /*IsCXXMethod=*/true));
588     EPI.HasTrailingReturn = true;
589     EPI.TypeQuals |= DeclSpec::TQ_const;
590     // C++1y [expr.prim.lambda]:
591     //   The lambda return type is 'auto', which is replaced by the
592     //   trailing-return type if provided and/or deduced from 'return'
593     //   statements
594     // We don't do this before C++1y, because we don't support deduced return
595     // types there.
596     QualType DefaultTypeForNoTrailingReturn =
597         getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
598                                   : Context.DependentTy;
599     QualType MethodTy =
600         Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
601     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
602     ExplicitParams = false;
603     ExplicitResultType = false;
604     EndLoc = Intro.Range.getEnd();
605   } else {
606     assert(ParamInfo.isFunctionDeclarator() &&
607            "lambda-declarator is a function");
608     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
609 
610     // C++11 [expr.prim.lambda]p5:
611     //   This function call operator is declared const (9.3.1) if and only if
612     //   the lambda-expression's parameter-declaration-clause is not followed
613     //   by mutable. It is neither virtual nor declared volatile. [...]
614     if (!FTI.hasMutableQualifier())
615       FTI.TypeQuals |= DeclSpec::TQ_const;
616 
617     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
618     assert(MethodTyInfo && "no type from lambda-declarator");
619     EndLoc = ParamInfo.getSourceRange().getEnd();
620 
621     ExplicitResultType = FTI.hasTrailingReturnType();
622 
623     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
624         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
625       // Empty arg list, don't push any params.
626       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
627     } else {
628       Params.reserve(FTI.NumArgs);
629       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
630         Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
631     }
632 
633     // Check for unexpanded parameter packs in the method type.
634     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
635       ContainsUnexpandedParameterPack = true;
636   }
637 
638   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
639                                                  KnownDependent, Intro.Default);
640 
641   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
642                                                 MethodTyInfo, EndLoc, Params);
643   if (ExplicitParams)
644     CheckCXXDefaultArguments(Method);
645 
646   // Attributes on the lambda apply to the method.
647   ProcessDeclAttributes(CurScope, Method, ParamInfo);
648 
649   // Introduce the function call operator as the current declaration context.
650   PushDeclContext(CurScope, Method);
651 
652   // Build the lambda scope.
653   buildLambdaScope(LSI, Method,
654                        Intro.Range,
655                        Intro.Default, Intro.DefaultLoc,
656                        ExplicitParams,
657                        ExplicitResultType,
658                        !Method->isConst());
659 
660   // Distinct capture names, for diagnostics.
661   llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
662 
663   // Handle explicit captures.
664   SourceLocation PrevCaptureLoc
665     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
666   for (SmallVectorImpl<LambdaCapture>::const_iterator
667          C = Intro.Captures.begin(),
668          E = Intro.Captures.end();
669        C != E;
670        PrevCaptureLoc = C->Loc, ++C) {
671     if (C->Kind == LCK_This) {
672       // C++11 [expr.prim.lambda]p8:
673       //   An identifier or this shall not appear more than once in a
674       //   lambda-capture.
675       if (LSI->isCXXThisCaptured()) {
676         Diag(C->Loc, diag::err_capture_more_than_once)
677           << "'this'"
678           << SourceRange(LSI->getCXXThisCapture().getLocation())
679           << FixItHint::CreateRemoval(
680                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
681         continue;
682       }
683 
684       // C++11 [expr.prim.lambda]p8:
685       //   If a lambda-capture includes a capture-default that is =, the
686       //   lambda-capture shall not contain this [...].
687       if (Intro.Default == LCD_ByCopy) {
688         Diag(C->Loc, diag::err_this_capture_with_copy_default)
689           << FixItHint::CreateRemoval(
690                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
691         continue;
692       }
693 
694       // C++11 [expr.prim.lambda]p12:
695       //   If this is captured by a local lambda expression, its nearest
696       //   enclosing function shall be a non-static member function.
697       QualType ThisCaptureType = getCurrentThisType();
698       if (ThisCaptureType.isNull()) {
699         Diag(C->Loc, diag::err_this_capture) << true;
700         continue;
701       }
702 
703       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
704       continue;
705     }
706 
707     assert(C->Id && "missing identifier for capture");
708 
709     if (C->Init.isInvalid())
710       continue;
711 
712     VarDecl *Var;
713     if (C->Init.isUsable()) {
714       Diag(C->Loc, getLangOpts().CPlusPlus1y
715                        ? diag::warn_cxx11_compat_init_capture
716                        : diag::ext_init_capture);
717 
718       if (C->Init.get()->containsUnexpandedParameterPack())
719         ContainsUnexpandedParameterPack = true;
720 
721       Var = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
722                              C->Id, C->Init.take());
723       // C++1y [expr.prim.lambda]p11:
724       //   An init-capture behaves as if it declares and explicitly
725       //   captures a variable [...] whose declarative region is the
726       //   lambda-expression's compound-statement
727       if (Var)
728         PushOnScopeChains(Var, CurScope, false);
729     } else {
730       // C++11 [expr.prim.lambda]p8:
731       //   If a lambda-capture includes a capture-default that is &, the
732       //   identifiers in the lambda-capture shall not be preceded by &.
733       //   If a lambda-capture includes a capture-default that is =, [...]
734       //   each identifier it contains shall be preceded by &.
735       if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
736         Diag(C->Loc, diag::err_reference_capture_with_reference_default)
737           << FixItHint::CreateRemoval(
738                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
739         continue;
740       } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
741         Diag(C->Loc, diag::err_copy_capture_with_copy_default)
742           << FixItHint::CreateRemoval(
743                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
744         continue;
745       }
746 
747       // C++11 [expr.prim.lambda]p10:
748       //   The identifiers in a capture-list are looked up using the usual
749       //   rules for unqualified name lookup (3.4.1)
750       DeclarationNameInfo Name(C->Id, C->Loc);
751       LookupResult R(*this, Name, LookupOrdinaryName);
752       LookupName(R, CurScope);
753       if (R.isAmbiguous())
754         continue;
755       if (R.empty()) {
756         // FIXME: Disable corrections that would add qualification?
757         CXXScopeSpec ScopeSpec;
758         DeclFilterCCC<VarDecl> Validator;
759         if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
760           continue;
761       }
762 
763       Var = R.getAsSingle<VarDecl>();
764     }
765 
766     // C++11 [expr.prim.lambda]p8:
767     //   An identifier or this shall not appear more than once in a
768     //   lambda-capture.
769     if (!CaptureNames.insert(C->Id)) {
770       if (Var && LSI->isCaptured(Var)) {
771         Diag(C->Loc, diag::err_capture_more_than_once)
772           << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
773           << FixItHint::CreateRemoval(
774                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
775       } else
776         // Previous capture captured something different (one or both was
777         // an init-cpature): no fixit.
778         Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
779       continue;
780     }
781 
782     // C++11 [expr.prim.lambda]p10:
783     //   [...] each such lookup shall find a variable with automatic storage
784     //   duration declared in the reaching scope of the local lambda expression.
785     // Note that the 'reaching scope' check happens in tryCaptureVariable().
786     if (!Var) {
787       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
788       continue;
789     }
790 
791     // Ignore invalid decls; they'll just confuse the code later.
792     if (Var->isInvalidDecl())
793       continue;
794 
795     if (!Var->hasLocalStorage()) {
796       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
797       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
798       continue;
799     }
800 
801     // C++11 [expr.prim.lambda]p23:
802     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
803     SourceLocation EllipsisLoc;
804     if (C->EllipsisLoc.isValid()) {
805       if (Var->isParameterPack()) {
806         EllipsisLoc = C->EllipsisLoc;
807       } else {
808         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
809           << SourceRange(C->Loc);
810 
811         // Just ignore the ellipsis.
812       }
813     } else if (Var->isParameterPack()) {
814       ContainsUnexpandedParameterPack = true;
815     }
816 
817     if (C->Init.isUsable()) {
818       buildInitCaptureField(LSI, Var);
819     } else {
820       TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
821                                                    TryCapture_ExplicitByVal;
822       tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
823     }
824   }
825   finishLambdaExplicitCaptures(LSI);
826 
827   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
828 
829   // Add lambda parameters into scope.
830   addLambdaParameters(Method, CurScope);
831 
832   // Enter a new evaluation context to insulate the lambda from any
833   // cleanups from the enclosing full-expression.
834   PushExpressionEvaluationContext(PotentiallyEvaluated);
835 }
836 
837 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
838                             bool IsInstantiation) {
839   // Leave the expression-evaluation context.
840   DiscardCleanupsInEvaluationContext();
841   PopExpressionEvaluationContext();
842 
843   // Leave the context of the lambda.
844   if (!IsInstantiation)
845     PopDeclContext();
846 
847   // Finalize the lambda.
848   LambdaScopeInfo *LSI = getCurLambda();
849   CXXRecordDecl *Class = LSI->Lambda;
850   Class->setInvalidDecl();
851   SmallVector<Decl*, 4> Fields;
852   for (RecordDecl::field_iterator i = Class->field_begin(),
853                                   e = Class->field_end(); i != e; ++i)
854     Fields.push_back(*i);
855   ActOnFields(0, Class->getLocation(), Class, Fields,
856               SourceLocation(), SourceLocation(), 0);
857   CheckCompletedCXXClass(Class);
858 
859   PopFunctionScopeInfo();
860 }
861 
862 /// \brief Add a lambda's conversion to function pointer, as described in
863 /// C++11 [expr.prim.lambda]p6.
864 static void addFunctionPointerConversion(Sema &S,
865                                          SourceRange IntroducerRange,
866                                          CXXRecordDecl *Class,
867                                          CXXMethodDecl *CallOperator) {
868   // Add the conversion to function pointer.
869   const FunctionProtoType *CallOpProto =
870       CallOperator->getType()->getAs<FunctionProtoType>();
871   const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
872       CallOpProto->getExtProtoInfo();
873   QualType PtrToFunctionTy;
874   QualType InvokerFunctionTy;
875   {
876     FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
877     CallingConv CC = S.Context.getDefaultCallingConvention(
878         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
879     InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
880     InvokerExtInfo.TypeQuals = 0;
881     assert(InvokerExtInfo.RefQualifier == RQ_None &&
882         "Lambda's call operator should not have a reference qualifier");
883     InvokerFunctionTy = S.Context.getFunctionType(CallOpProto->getResultType(),
884         CallOpProto->getArgTypes(), InvokerExtInfo);
885     PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
886   }
887 
888   // Create the type of the conversion function.
889   FunctionProtoType::ExtProtoInfo ConvExtInfo(
890       S.Context.getDefaultCallingConvention(
891       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
892   // The conversion function is always const.
893   ConvExtInfo.TypeQuals = Qualifiers::Const;
894   QualType ConvTy =
895       S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
896 
897   SourceLocation Loc = IntroducerRange.getBegin();
898   DeclarationName ConversionName
899     = S.Context.DeclarationNames.getCXXConversionFunctionName(
900         S.Context.getCanonicalType(PtrToFunctionTy));
901   DeclarationNameLoc ConvNameLoc;
902   // Construct a TypeSourceInfo for the conversion function, and wire
903   // all the parameters appropriately for the FunctionProtoTypeLoc
904   // so that everything works during transformation/instantiation of
905   // generic lambdas.
906   // The main reason for wiring up the parameters of the conversion
907   // function with that of the call operator is so that constructs
908   // like the following work:
909   // auto L = [](auto b) {                <-- 1
910   //   return [](auto a) -> decltype(a) { <-- 2
911   //      return a;
912   //   };
913   // };
914   // int (*fp)(int) = L(5);
915   // Because the trailing return type can contain DeclRefExprs that refer
916   // to the original call operator's variables, we hijack the call
917   // operators ParmVarDecls below.
918   TypeSourceInfo *ConvNamePtrToFunctionTSI =
919       S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
920   ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
921 
922   // The conversion function is a conversion to a pointer-to-function.
923   TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
924   FunctionProtoTypeLoc ConvTL =
925       ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
926   // Get the result of the conversion function which is a pointer-to-function.
927   PointerTypeLoc PtrToFunctionTL =
928       ConvTL.getResultLoc().getAs<PointerTypeLoc>();
929   // Do the same for the TypeSourceInfo that is used to name the conversion
930   // operator.
931   PointerTypeLoc ConvNamePtrToFunctionTL =
932       ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
933 
934   // Get the underlying function types that the conversion function will
935   // be converting to (should match the type of the call operator).
936   FunctionProtoTypeLoc CallOpConvTL =
937       PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
938   FunctionProtoTypeLoc CallOpConvNameTL =
939     ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
940 
941   // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
942   // These parameter's are essentially used to transform the name and
943   // the type of the conversion operator.  By using the same parameters
944   // as the call operator's we don't have to fix any back references that
945   // the trailing return type of the call operator's uses (such as
946   // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
947   // - we can simply use the return type of the call operator, and
948   // everything should work.
949   SmallVector<ParmVarDecl *, 4> InvokerParams;
950   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
951     ParmVarDecl *From = CallOperator->getParamDecl(I);
952 
953     InvokerParams.push_back(ParmVarDecl::Create(S.Context,
954            // Temporarily add to the TU. This is set to the invoker below.
955                                              S.Context.getTranslationUnitDecl(),
956                                              From->getLocStart(),
957                                              From->getLocation(),
958                                              From->getIdentifier(),
959                                              From->getType(),
960                                              From->getTypeSourceInfo(),
961                                              From->getStorageClass(),
962                                              /*DefaultArg=*/0));
963     CallOpConvTL.setArg(I, From);
964     CallOpConvNameTL.setArg(I, From);
965   }
966 
967   CXXConversionDecl *Conversion
968     = CXXConversionDecl::Create(S.Context, Class, Loc,
969                                 DeclarationNameInfo(ConversionName,
970                                   Loc, ConvNameLoc),
971                                 ConvTy,
972                                 ConvTSI,
973                                 /*isInline=*/true, /*isExplicit=*/false,
974                                 /*isConstexpr=*/false,
975                                 CallOperator->getBody()->getLocEnd());
976   Conversion->setAccess(AS_public);
977   Conversion->setImplicit(true);
978 
979   if (Class->isGenericLambda()) {
980     // Create a template version of the conversion operator, using the template
981     // parameter list of the function call operator.
982     FunctionTemplateDecl *TemplateCallOperator =
983             CallOperator->getDescribedFunctionTemplate();
984     FunctionTemplateDecl *ConversionTemplate =
985                   FunctionTemplateDecl::Create(S.Context, Class,
986                                       Loc, ConversionName,
987                                       TemplateCallOperator->getTemplateParameters(),
988                                       Conversion);
989     ConversionTemplate->setAccess(AS_public);
990     ConversionTemplate->setImplicit(true);
991     Conversion->setDescribedFunctionTemplate(ConversionTemplate);
992     Class->addDecl(ConversionTemplate);
993   } else
994     Class->addDecl(Conversion);
995   // Add a non-static member function that will be the result of
996   // the conversion with a certain unique ID.
997   DeclarationName InvokerName = &S.Context.Idents.get(
998                                                  getLambdaStaticInvokerName());
999   // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1000   // we should get a prebuilt TrivialTypeSourceInfo from Context
1001   // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1002   // then rewire the parameters accordingly, by hoisting up the InvokeParams
1003   // loop below and then use its Params to set Invoke->setParams(...) below.
1004   // This would avoid the 'const' qualifier of the calloperator from
1005   // contaminating the type of the invoker, which is currently adjusted
1006   // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1007   // trailing return type of the invoker would require a visitor to rebuild
1008   // the trailing return type and adjusting all back DeclRefExpr's to refer
1009   // to the new static invoker parameters - not the call operator's.
1010   CXXMethodDecl *Invoke
1011     = CXXMethodDecl::Create(S.Context, Class, Loc,
1012                             DeclarationNameInfo(InvokerName, Loc),
1013                             InvokerFunctionTy,
1014                             CallOperator->getTypeSourceInfo(),
1015                             SC_Static, /*IsInline=*/true,
1016                             /*IsConstexpr=*/false,
1017                             CallOperator->getBody()->getLocEnd());
1018   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1019     InvokerParams[I]->setOwningFunction(Invoke);
1020   Invoke->setParams(InvokerParams);
1021   Invoke->setAccess(AS_private);
1022   Invoke->setImplicit(true);
1023   if (Class->isGenericLambda()) {
1024     FunctionTemplateDecl *TemplateCallOperator =
1025             CallOperator->getDescribedFunctionTemplate();
1026     FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1027                           S.Context, Class, Loc, InvokerName,
1028                           TemplateCallOperator->getTemplateParameters(),
1029                           Invoke);
1030     StaticInvokerTemplate->setAccess(AS_private);
1031     StaticInvokerTemplate->setImplicit(true);
1032     Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1033     Class->addDecl(StaticInvokerTemplate);
1034   } else
1035     Class->addDecl(Invoke);
1036 }
1037 
1038 /// \brief Add a lambda's conversion to block pointer.
1039 static void addBlockPointerConversion(Sema &S,
1040                                       SourceRange IntroducerRange,
1041                                       CXXRecordDecl *Class,
1042                                       CXXMethodDecl *CallOperator) {
1043   const FunctionProtoType *Proto
1044     = CallOperator->getType()->getAs<FunctionProtoType>();
1045   QualType BlockPtrTy;
1046   {
1047     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1048     ExtInfo.TypeQuals = 0;
1049     QualType FunctionTy = S.Context.getFunctionType(
1050         Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
1051     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1052   }
1053 
1054   FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1055       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1056   ExtInfo.TypeQuals = Qualifiers::Const;
1057   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
1058 
1059   SourceLocation Loc = IntroducerRange.getBegin();
1060   DeclarationName Name
1061     = S.Context.DeclarationNames.getCXXConversionFunctionName(
1062         S.Context.getCanonicalType(BlockPtrTy));
1063   DeclarationNameLoc NameLoc;
1064   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1065   CXXConversionDecl *Conversion
1066     = CXXConversionDecl::Create(S.Context, Class, Loc,
1067                                 DeclarationNameInfo(Name, Loc, NameLoc),
1068                                 ConvTy,
1069                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1070                                 /*isInline=*/true, /*isExplicit=*/false,
1071                                 /*isConstexpr=*/false,
1072                                 CallOperator->getBody()->getLocEnd());
1073   Conversion->setAccess(AS_public);
1074   Conversion->setImplicit(true);
1075   Class->addDecl(Conversion);
1076 }
1077 
1078 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1079                                  Scope *CurScope,
1080                                  bool IsInstantiation) {
1081   // Collect information from the lambda scope.
1082   SmallVector<LambdaExpr::Capture, 4> Captures;
1083   SmallVector<Expr *, 4> CaptureInits;
1084   LambdaCaptureDefault CaptureDefault;
1085   SourceLocation CaptureDefaultLoc;
1086   CXXRecordDecl *Class;
1087   CXXMethodDecl *CallOperator;
1088   SourceRange IntroducerRange;
1089   bool ExplicitParams;
1090   bool ExplicitResultType;
1091   bool LambdaExprNeedsCleanups;
1092   bool ContainsUnexpandedParameterPack;
1093   SmallVector<VarDecl *, 4> ArrayIndexVars;
1094   SmallVector<unsigned, 4> ArrayIndexStarts;
1095   {
1096     LambdaScopeInfo *LSI = getCurLambda();
1097     CallOperator = LSI->CallOperator;
1098     Class = LSI->Lambda;
1099     IntroducerRange = LSI->IntroducerRange;
1100     ExplicitParams = LSI->ExplicitParams;
1101     ExplicitResultType = !LSI->HasImplicitReturnType;
1102     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
1103     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1104     ArrayIndexVars.swap(LSI->ArrayIndexVars);
1105     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1106 
1107     // Translate captures.
1108     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1109       LambdaScopeInfo::Capture From = LSI->Captures[I];
1110       assert(!From.isBlockCapture() && "Cannot capture __block variables");
1111       bool IsImplicit = I >= LSI->NumExplicitCaptures;
1112 
1113       // Handle 'this' capture.
1114       if (From.isThisCapture()) {
1115         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1116                                                IsImplicit,
1117                                                LCK_This));
1118         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1119                                                          getCurrentThisType(),
1120                                                          /*isImplicit=*/true));
1121         continue;
1122       }
1123 
1124       VarDecl *Var = From.getVariable();
1125       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1126       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
1127                                              Kind, Var, From.getEllipsisLoc()));
1128       CaptureInits.push_back(From.getInitExpr());
1129     }
1130 
1131     switch (LSI->ImpCaptureStyle) {
1132     case CapturingScopeInfo::ImpCap_None:
1133       CaptureDefault = LCD_None;
1134       break;
1135 
1136     case CapturingScopeInfo::ImpCap_LambdaByval:
1137       CaptureDefault = LCD_ByCopy;
1138       break;
1139 
1140     case CapturingScopeInfo::ImpCap_CapturedRegion:
1141     case CapturingScopeInfo::ImpCap_LambdaByref:
1142       CaptureDefault = LCD_ByRef;
1143       break;
1144 
1145     case CapturingScopeInfo::ImpCap_Block:
1146       llvm_unreachable("block capture in lambda");
1147       break;
1148     }
1149     CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1150 
1151     // C++11 [expr.prim.lambda]p4:
1152     //   If a lambda-expression does not include a
1153     //   trailing-return-type, it is as if the trailing-return-type
1154     //   denotes the following type:
1155     //
1156     // Skip for C++1y return type deduction semantics which uses
1157     // different machinery.
1158     // FIXME: Refactor and Merge the return type deduction machinery.
1159     // FIXME: Assumes current resolution to core issue 975.
1160     if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
1161       deduceClosureReturnType(*LSI);
1162 
1163       //   - if there are no return statements in the
1164       //     compound-statement, or all return statements return
1165       //     either an expression of type void or no expression or
1166       //     braced-init-list, the type void;
1167       if (LSI->ReturnType.isNull()) {
1168         LSI->ReturnType = Context.VoidTy;
1169       }
1170 
1171       // Create a function type with the inferred return type.
1172       const FunctionProtoType *Proto
1173         = CallOperator->getType()->getAs<FunctionProtoType>();
1174       QualType FunctionTy = Context.getFunctionType(
1175           LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
1176       CallOperator->setType(FunctionTy);
1177     }
1178     // C++ [expr.prim.lambda]p7:
1179     //   The lambda-expression's compound-statement yields the
1180     //   function-body (8.4) of the function call operator [...].
1181     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
1182     CallOperator->setLexicalDeclContext(Class);
1183     Decl *TemplateOrNonTemplateCallOperatorDecl =
1184         CallOperator->getDescribedFunctionTemplate()
1185         ? CallOperator->getDescribedFunctionTemplate()
1186         : cast<Decl>(CallOperator);
1187 
1188     TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1189     Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1190 
1191     PopExpressionEvaluationContext();
1192 
1193     // C++11 [expr.prim.lambda]p6:
1194     //   The closure type for a lambda-expression with no lambda-capture
1195     //   has a public non-virtual non-explicit const conversion function
1196     //   to pointer to function having the same parameter and return
1197     //   types as the closure type's function call operator.
1198     if (Captures.empty() && CaptureDefault == LCD_None)
1199       addFunctionPointerConversion(*this, IntroducerRange, Class,
1200                                    CallOperator);
1201 
1202     // Objective-C++:
1203     //   The closure type for a lambda-expression has a public non-virtual
1204     //   non-explicit const conversion function to a block pointer having the
1205     //   same parameter and return types as the closure type's function call
1206     //   operator.
1207     // FIXME: Fix generic lambda to block conversions.
1208     if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1209                                               !Class->isGenericLambda())
1210       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1211 
1212     // Finalize the lambda class.
1213     SmallVector<Decl*, 4> Fields;
1214     for (RecordDecl::field_iterator i = Class->field_begin(),
1215                                     e = Class->field_end(); i != e; ++i)
1216       Fields.push_back(*i);
1217     ActOnFields(0, Class->getLocation(), Class, Fields,
1218                 SourceLocation(), SourceLocation(), 0);
1219     CheckCompletedCXXClass(Class);
1220   }
1221 
1222   if (LambdaExprNeedsCleanups)
1223     ExprNeedsCleanups = true;
1224 
1225   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1226                                           CaptureDefault, CaptureDefaultLoc,
1227                                           Captures,
1228                                           ExplicitParams, ExplicitResultType,
1229                                           CaptureInits, ArrayIndexVars,
1230                                           ArrayIndexStarts, Body->getLocEnd(),
1231                                           ContainsUnexpandedParameterPack);
1232   // C++11 [expr.prim.lambda]p2:
1233   //   A lambda-expression shall not appear in an unevaluated operand
1234   //   (Clause 5).
1235   if (!CurContext->isDependentContext()) {
1236     switch (ExprEvalContexts.back().Context) {
1237     case Unevaluated:
1238     case UnevaluatedAbstract:
1239       // We don't actually diagnose this case immediately, because we
1240       // could be within a context where we might find out later that
1241       // the expression is potentially evaluated (e.g., for typeid).
1242       ExprEvalContexts.back().Lambdas.push_back(Lambda);
1243       break;
1244 
1245     case ConstantEvaluated:
1246     case PotentiallyEvaluated:
1247     case PotentiallyEvaluatedIfUsed:
1248       break;
1249     }
1250   }
1251   // TODO: Implement capturing.
1252   if (Lambda->isGenericLambda()) {
1253     if (!Captures.empty() || Lambda->getCaptureDefault() != LCD_None) {
1254       Diag(Lambda->getIntroducerRange().getBegin(),
1255         diag::err_glambda_not_fully_implemented)
1256         << " capturing not implemented yet";
1257       return ExprError();
1258     }
1259   }
1260   return MaybeBindToTemporary(Lambda);
1261 }
1262 
1263 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1264                                                SourceLocation ConvLocation,
1265                                                CXXConversionDecl *Conv,
1266                                                Expr *Src) {
1267   // Make sure that the lambda call operator is marked used.
1268   CXXRecordDecl *Lambda = Conv->getParent();
1269   CXXMethodDecl *CallOperator
1270     = cast<CXXMethodDecl>(
1271         Lambda->lookup(
1272           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1273   CallOperator->setReferenced();
1274   CallOperator->markUsed(Context);
1275 
1276   ExprResult Init = PerformCopyInitialization(
1277                       InitializedEntity::InitializeBlock(ConvLocation,
1278                                                          Src->getType(),
1279                                                          /*NRVO=*/false),
1280                       CurrentLocation, Src);
1281   if (!Init.isInvalid())
1282     Init = ActOnFinishFullExpr(Init.take());
1283 
1284   if (Init.isInvalid())
1285     return ExprError();
1286 
1287   // Create the new block to be returned.
1288   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1289 
1290   // Set the type information.
1291   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1292   Block->setIsVariadic(CallOperator->isVariadic());
1293   Block->setBlockMissingReturnType(false);
1294 
1295   // Add parameters.
1296   SmallVector<ParmVarDecl *, 4> BlockParams;
1297   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1298     ParmVarDecl *From = CallOperator->getParamDecl(I);
1299     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1300                                               From->getLocStart(),
1301                                               From->getLocation(),
1302                                               From->getIdentifier(),
1303                                               From->getType(),
1304                                               From->getTypeSourceInfo(),
1305                                               From->getStorageClass(),
1306                                               /*DefaultArg=*/0));
1307   }
1308   Block->setParams(BlockParams);
1309 
1310   Block->setIsConversionFromLambda(true);
1311 
1312   // Add capture. The capture uses a fake variable, which doesn't correspond
1313   // to any actual memory location. However, the initializer copy-initializes
1314   // the lambda object.
1315   TypeSourceInfo *CapVarTSI =
1316       Context.getTrivialTypeSourceInfo(Src->getType());
1317   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1318                                     ConvLocation, 0,
1319                                     Src->getType(), CapVarTSI,
1320                                     SC_None);
1321   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1322                              /*Nested=*/false, /*Copy=*/Init.take());
1323   Block->setCaptures(Context, &Capture, &Capture + 1,
1324                      /*CapturesCXXThis=*/false);
1325 
1326   // Add a fake function body to the block. IR generation is responsible
1327   // for filling in the actual body, which cannot be expressed as an AST.
1328   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1329 
1330   // Create the block literal expression.
1331   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1332   ExprCleanupObjects.push_back(Block);
1333   ExprNeedsCleanups = true;
1334 
1335   return BuildBlock;
1336 }
1337