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/ExprCXX.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/SemaInternal.h"
21 using namespace clang;
22 using namespace sema;
23 
24 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25                                              TypeSourceInfo *Info,
26                                              bool KnownDependent) {
27   DeclContext *DC = CurContext;
28   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
29     DC = DC->getParent();
30 
31   // Start constructing the lambda class.
32   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
33                                                      IntroducerRange.getBegin(),
34                                                      KnownDependent);
35   DC->addDecl(Class);
36 
37   return Class;
38 }
39 
40 /// \brief Determine whether the given context is or is enclosed in an inline
41 /// function.
42 static bool isInInlineFunction(const DeclContext *DC) {
43   while (!DC->isFileContext()) {
44     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
45       if (FD->isInlined())
46         return true;
47 
48     DC = DC->getLexicalParent();
49   }
50 
51   return false;
52 }
53 
54 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
55                  SourceRange IntroducerRange,
56                  TypeSourceInfo *MethodType,
57                  SourceLocation EndLoc,
58                  ArrayRef<ParmVarDecl *> Params) {
59   // C++11 [expr.prim.lambda]p5:
60   //   The closure type for a lambda-expression has a public inline function
61   //   call operator (13.5.4) whose parameters and return type are described by
62   //   the lambda-expression's parameter-declaration-clause and
63   //   trailing-return-type respectively.
64   DeclarationName MethodName
65     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
66   DeclarationNameLoc MethodNameLoc;
67   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
68     = IntroducerRange.getBegin().getRawEncoding();
69   MethodNameLoc.CXXOperatorName.EndOpNameLoc
70     = IntroducerRange.getEnd().getRawEncoding();
71   CXXMethodDecl *Method
72     = CXXMethodDecl::Create(Context, Class, EndLoc,
73                             DeclarationNameInfo(MethodName,
74                                                 IntroducerRange.getBegin(),
75                                                 MethodNameLoc),
76                             MethodType->getType(), MethodType,
77                             SC_None,
78                             /*isInline=*/true,
79                             /*isConstExpr=*/false,
80                             EndLoc);
81   Method->setAccess(AS_public);
82 
83   // Temporarily set the lexical declaration context to the current
84   // context, so that the Scope stack matches the lexical nesting.
85   Method->setLexicalDeclContext(CurContext);
86 
87   // Add parameters.
88   if (!Params.empty()) {
89     Method->setParams(Params);
90     CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
91                              const_cast<ParmVarDecl **>(Params.end()),
92                              /*CheckParameterNames=*/false);
93 
94     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
95                                     PEnd = Method->param_end();
96          P != PEnd; ++P)
97       (*P)->setOwningFunction(Method);
98   }
99 
100   // Allocate a mangling number for this lambda expression, if the ABI
101   // requires one.
102   Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
103 
104   enum ContextKind {
105     Normal,
106     DefaultArgument,
107     DataMember,
108     StaticDataMember
109   } Kind = Normal;
110 
111   // Default arguments of member function parameters that appear in a class
112   // definition, as well as the initializers of data members, receive special
113   // treatment. Identify them.
114   if (ContextDecl) {
115     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
116       if (const DeclContext *LexicalDC
117           = Param->getDeclContext()->getLexicalParent())
118         if (LexicalDC->isRecord())
119           Kind = DefaultArgument;
120     } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
121       if (Var->getDeclContext()->isRecord())
122         Kind = StaticDataMember;
123     } else if (isa<FieldDecl>(ContextDecl)) {
124       Kind = DataMember;
125     }
126   }
127 
128   // Itanium ABI [5.1.7]:
129   //   In the following contexts [...] the one-definition rule requires closure
130   //   types in different translation units to "correspond":
131   bool IsInNonspecializedTemplate =
132     !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
133   unsigned ManglingNumber;
134   switch (Kind) {
135   case Normal:
136     //  -- the bodies of non-exported nonspecialized template functions
137     //  -- the bodies of inline functions
138     if ((IsInNonspecializedTemplate &&
139          !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
140         isInInlineFunction(CurContext))
141       ManglingNumber = Context.getLambdaManglingNumber(Method);
142     else
143       ManglingNumber = 0;
144 
145     // There is no special context for this lambda.
146     ContextDecl = 0;
147     break;
148 
149   case StaticDataMember:
150     //  -- the initializers of nonspecialized static members of template classes
151     if (!IsInNonspecializedTemplate) {
152       ManglingNumber = 0;
153       ContextDecl = 0;
154       break;
155     }
156     // Fall through to assign a mangling number.
157 
158   case DataMember:
159     //  -- the in-class initializers of class members
160   case DefaultArgument:
161     //  -- default arguments appearing in class definitions
162     ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
163                        .getManglingNumber(Method);
164     break;
165   }
166 
167   Class->setLambdaMangling(ManglingNumber, ContextDecl);
168 
169   return Method;
170 }
171 
172 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
173                                         SourceRange IntroducerRange,
174                                         LambdaCaptureDefault CaptureDefault,
175                                         bool ExplicitParams,
176                                         bool ExplicitResultType,
177                                         bool Mutable) {
178   PushLambdaScope(CallOperator->getParent(), CallOperator);
179   LambdaScopeInfo *LSI = getCurLambda();
180   if (CaptureDefault == LCD_ByCopy)
181     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
182   else if (CaptureDefault == LCD_ByRef)
183     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
184   LSI->IntroducerRange = IntroducerRange;
185   LSI->ExplicitParams = ExplicitParams;
186   LSI->Mutable = Mutable;
187 
188   if (ExplicitResultType) {
189     LSI->ReturnType = CallOperator->getResultType();
190 
191     if (!LSI->ReturnType->isDependentType() &&
192         !LSI->ReturnType->isVoidType()) {
193       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
194                               diag::err_lambda_incomplete_result)) {
195         // Do nothing.
196       } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
197         Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
198           << LSI->ReturnType;
199       }
200     }
201   } else {
202     LSI->HasImplicitReturnType = true;
203   }
204 
205   return LSI;
206 }
207 
208 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
209   LSI->finishedExplicitCaptures();
210 }
211 
212 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
213   // Introduce our parameters into the function scope
214   for (unsigned p = 0, NumParams = CallOperator->getNumParams();
215        p < NumParams; ++p) {
216     ParmVarDecl *Param = CallOperator->getParamDecl(p);
217 
218     // If this has an identifier, add it to the scope stack.
219     if (CurScope && Param->getIdentifier()) {
220       CheckShadow(CurScope, Param);
221 
222       PushOnScopeChains(Param, CurScope);
223     }
224   }
225 }
226 
227 /// If this expression is an enumerator-like expression of some type
228 /// T, return the type T; otherwise, return null.
229 ///
230 /// Pointer comparisons on the result here should always work because
231 /// it's derived from either the parent of an EnumConstantDecl
232 /// (i.e. the definition) or the declaration returned by
233 /// EnumType::getDecl() (i.e. the definition).
234 static EnumDecl *findEnumForBlockReturn(Expr *E) {
235   // An expression is an enumerator-like expression of type T if,
236   // ignoring parens and parens-like expressions:
237   E = E->IgnoreParens();
238 
239   //  - it is an enumerator whose enum type is T or
240   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
241     if (EnumConstantDecl *D
242           = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
243       return cast<EnumDecl>(D->getDeclContext());
244     }
245     return 0;
246   }
247 
248   //  - it is a comma expression whose RHS is an enumerator-like
249   //    expression of type T or
250   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
251     if (BO->getOpcode() == BO_Comma)
252       return findEnumForBlockReturn(BO->getRHS());
253     return 0;
254   }
255 
256   //  - it is a statement-expression whose value expression is an
257   //    enumerator-like expression of type T or
258   if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
259     if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
260       return findEnumForBlockReturn(last);
261     return 0;
262   }
263 
264   //   - it is a ternary conditional operator (not the GNU ?:
265   //     extension) whose second and third operands are
266   //     enumerator-like expressions of type T or
267   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
268     if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
269       if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
270         return ED;
271     return 0;
272   }
273 
274   // (implicitly:)
275   //   - it is an implicit integral conversion applied to an
276   //     enumerator-like expression of type T or
277   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
278     // We can sometimes see integral conversions in valid
279     // enumerator-like expressions.
280     if (ICE->getCastKind() == CK_IntegralCast)
281       return findEnumForBlockReturn(ICE->getSubExpr());
282 
283     // Otherwise, just rely on the type.
284   }
285 
286   //   - it is an expression of that formal enum type.
287   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
288     return ET->getDecl();
289   }
290 
291   // Otherwise, nope.
292   return 0;
293 }
294 
295 /// Attempt to find a type T for which the returned expression of the
296 /// given statement is an enumerator-like expression of that type.
297 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
298   if (Expr *retValue = ret->getRetValue())
299     return findEnumForBlockReturn(retValue);
300   return 0;
301 }
302 
303 /// Attempt to find a common type T for which all of the returned
304 /// expressions in a block are enumerator-like expressions of that
305 /// type.
306 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
307   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
308 
309   // Try to find one for the first return.
310   EnumDecl *ED = findEnumForBlockReturn(*i);
311   if (!ED) return 0;
312 
313   // Check that the rest of the returns have the same enum.
314   for (++i; i != e; ++i) {
315     if (findEnumForBlockReturn(*i) != ED)
316       return 0;
317   }
318 
319   // Never infer an anonymous enum type.
320   if (!ED->hasNameForLinkage()) return 0;
321 
322   return ED;
323 }
324 
325 /// Adjust the given return statements so that they formally return
326 /// the given type.  It should require, at most, an IntegralCast.
327 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
328                                      QualType returnType) {
329   for (ArrayRef<ReturnStmt*>::iterator
330          i = returns.begin(), e = returns.end(); i != e; ++i) {
331     ReturnStmt *ret = *i;
332     Expr *retValue = ret->getRetValue();
333     if (S.Context.hasSameType(retValue->getType(), returnType))
334       continue;
335 
336     // Right now we only support integral fixup casts.
337     assert(returnType->isIntegralOrUnscopedEnumerationType());
338     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
339 
340     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
341 
342     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
343     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
344                                  E, /*base path*/ 0, VK_RValue);
345     if (cleanups) {
346       cleanups->setSubExpr(E);
347     } else {
348       ret->setRetValue(E);
349     }
350   }
351 }
352 
353 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
354   assert(CSI.HasImplicitReturnType);
355 
356   // C++ Core Issue #975, proposed resolution:
357   //   If a lambda-expression does not include a trailing-return-type,
358   //   it is as if the trailing-return-type denotes the following type:
359   //     - if there are no return statements in the compound-statement,
360   //       or all return statements return either an expression of type
361   //       void or no expression or braced-init-list, the type void;
362   //     - otherwise, if all return statements return an expression
363   //       and the types of the returned expressions after
364   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
365   //       array-to-pointer conversion (4.2 [conv.array]), and
366   //       function-to-pointer conversion (4.3 [conv.func]) are the
367   //       same, that common type;
368   //     - otherwise, the program is ill-formed.
369   //
370   // In addition, in blocks in non-C++ modes, if all of the return
371   // statements are enumerator-like expressions of some type T, where
372   // T has a name for linkage, then we infer the return type of the
373   // block to be that type.
374 
375   // First case: no return statements, implicit void return type.
376   ASTContext &Ctx = getASTContext();
377   if (CSI.Returns.empty()) {
378     // It's possible there were simply no /valid/ return statements.
379     // In this case, the first one we found may have at least given us a type.
380     if (CSI.ReturnType.isNull())
381       CSI.ReturnType = Ctx.VoidTy;
382     return;
383   }
384 
385   // Second case: at least one return statement has dependent type.
386   // Delay type checking until instantiation.
387   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
388   if (CSI.ReturnType->isDependentType())
389     return;
390 
391   // Try to apply the enum-fuzz rule.
392   if (!getLangOpts().CPlusPlus) {
393     assert(isa<BlockScopeInfo>(CSI));
394     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
395     if (ED) {
396       CSI.ReturnType = Context.getTypeDeclType(ED);
397       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
398       return;
399     }
400   }
401 
402   // Third case: only one return statement. Don't bother doing extra work!
403   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
404                                          E = CSI.Returns.end();
405   if (I+1 == E)
406     return;
407 
408   // General case: many return statements.
409   // Check that they all have compatible return types.
410 
411   // We require the return types to strictly match here.
412   // Note that we've already done the required promotions as part of
413   // processing the return statement.
414   for (; I != E; ++I) {
415     const ReturnStmt *RS = *I;
416     const Expr *RetE = RS->getRetValue();
417 
418     QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
419     if (Context.hasSameType(ReturnType, CSI.ReturnType))
420       continue;
421 
422     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
423     // TODO: It's possible that the *first* return is the divergent one.
424     Diag(RS->getLocStart(),
425          diag::err_typecheck_missing_return_type_incompatible)
426       << ReturnType << CSI.ReturnType
427       << isa<LambdaScopeInfo>(CSI);
428     // Continue iterating so that we keep emitting diagnostics.
429   }
430 }
431 
432 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
433                                         Declarator &ParamInfo,
434                                         Scope *CurScope) {
435   // Determine if we're within a context where we know that the lambda will
436   // be dependent, because there are template parameters in scope.
437   bool KnownDependent = false;
438   if (Scope *TmplScope = CurScope->getTemplateParamParent())
439     if (!TmplScope->decl_empty())
440       KnownDependent = true;
441 
442   // Determine the signature of the call operator.
443   TypeSourceInfo *MethodTyInfo;
444   bool ExplicitParams = true;
445   bool ExplicitResultType = true;
446   bool ContainsUnexpandedParameterPack = false;
447   SourceLocation EndLoc;
448   SmallVector<ParmVarDecl *, 8> Params;
449   if (ParamInfo.getNumTypeObjects() == 0) {
450     // C++11 [expr.prim.lambda]p4:
451     //   If a lambda-expression does not include a lambda-declarator, it is as
452     //   if the lambda-declarator were ().
453     FunctionProtoType::ExtProtoInfo EPI;
454     EPI.HasTrailingReturn = true;
455     EPI.TypeQuals |= DeclSpec::TQ_const;
456     QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
457                                                 EPI);
458     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
459     ExplicitParams = false;
460     ExplicitResultType = false;
461     EndLoc = Intro.Range.getEnd();
462   } else {
463     assert(ParamInfo.isFunctionDeclarator() &&
464            "lambda-declarator is a function");
465     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
466 
467     // C++11 [expr.prim.lambda]p5:
468     //   This function call operator is declared const (9.3.1) if and only if
469     //   the lambda-expression's parameter-declaration-clause is not followed
470     //   by mutable. It is neither virtual nor declared volatile. [...]
471     if (!FTI.hasMutableQualifier())
472       FTI.TypeQuals |= DeclSpec::TQ_const;
473 
474     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
475     assert(MethodTyInfo && "no type from lambda-declarator");
476     EndLoc = ParamInfo.getSourceRange().getEnd();
477 
478     ExplicitResultType
479       = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
480                                                         != Context.DependentTy;
481 
482     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
483         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
484       // Empty arg list, don't push any params.
485       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
486     } else {
487       Params.reserve(FTI.NumArgs);
488       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
489         Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
490     }
491 
492     // Check for unexpanded parameter packs in the method type.
493     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
494       ContainsUnexpandedParameterPack = true;
495   }
496 
497   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
498                                                  KnownDependent);
499 
500   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
501                                                 MethodTyInfo, EndLoc, Params);
502 
503   if (ExplicitParams)
504     CheckCXXDefaultArguments(Method);
505 
506   // Attributes on the lambda apply to the method.
507   ProcessDeclAttributes(CurScope, Method, ParamInfo);
508 
509   // Introduce the function call operator as the current declaration context.
510   PushDeclContext(CurScope, Method);
511 
512   // Introduce the lambda scope.
513   LambdaScopeInfo *LSI
514     = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
515                        ExplicitResultType,
516                        !Method->isConst());
517 
518   // Handle explicit captures.
519   SourceLocation PrevCaptureLoc
520     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
521   for (SmallVector<LambdaCapture, 4>::const_iterator
522          C = Intro.Captures.begin(),
523          E = Intro.Captures.end();
524        C != E;
525        PrevCaptureLoc = C->Loc, ++C) {
526     if (C->Kind == LCK_This) {
527       // C++11 [expr.prim.lambda]p8:
528       //   An identifier or this shall not appear more than once in a
529       //   lambda-capture.
530       if (LSI->isCXXThisCaptured()) {
531         Diag(C->Loc, diag::err_capture_more_than_once)
532           << "'this'"
533           << SourceRange(LSI->getCXXThisCapture().getLocation())
534           << FixItHint::CreateRemoval(
535                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
536         continue;
537       }
538 
539       // C++11 [expr.prim.lambda]p8:
540       //   If a lambda-capture includes a capture-default that is =, the
541       //   lambda-capture shall not contain this [...].
542       if (Intro.Default == LCD_ByCopy) {
543         Diag(C->Loc, diag::err_this_capture_with_copy_default)
544           << FixItHint::CreateRemoval(
545                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
546         continue;
547       }
548 
549       // C++11 [expr.prim.lambda]p12:
550       //   If this is captured by a local lambda expression, its nearest
551       //   enclosing function shall be a non-static member function.
552       QualType ThisCaptureType = getCurrentThisType();
553       if (ThisCaptureType.isNull()) {
554         Diag(C->Loc, diag::err_this_capture) << true;
555         continue;
556       }
557 
558       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
559       continue;
560     }
561 
562     // FIXME: C++1y [expr.prim.lambda]p11
563     if (C->Init.isInvalid())
564       continue;
565     if (C->Init.isUsable()) {
566       Diag(C->Loc, diag::err_lambda_init_capture_unsupported);
567       continue;
568     }
569 
570     assert(C->Id && "missing identifier for capture");
571 
572     // C++11 [expr.prim.lambda]p8:
573     //   If a lambda-capture includes a capture-default that is &, the
574     //   identifiers in the lambda-capture shall not be preceded by &.
575     //   If a lambda-capture includes a capture-default that is =, [...]
576     //   each identifier it contains shall be preceded by &.
577     if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
578       Diag(C->Loc, diag::err_reference_capture_with_reference_default)
579         << FixItHint::CreateRemoval(
580              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
581       continue;
582     } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
583       Diag(C->Loc, diag::err_copy_capture_with_copy_default)
584         << FixItHint::CreateRemoval(
585              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
586       continue;
587     }
588 
589     DeclarationNameInfo Name(C->Id, C->Loc);
590     LookupResult R(*this, Name, LookupOrdinaryName);
591     LookupName(R, CurScope);
592     if (R.isAmbiguous())
593       continue;
594     if (R.empty()) {
595       // FIXME: Disable corrections that would add qualification?
596       CXXScopeSpec ScopeSpec;
597       DeclFilterCCC<VarDecl> Validator;
598       if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
599         continue;
600     }
601 
602     // C++11 [expr.prim.lambda]p10:
603     //   The identifiers in a capture-list are looked up using the usual rules
604     //   for unqualified name lookup (3.4.1); each such lookup shall find a
605     //   variable with automatic storage duration declared in the reaching
606     //   scope of the local lambda expression.
607     //
608     // Note that the 'reaching scope' check happens in tryCaptureVariable().
609     VarDecl *Var = R.getAsSingle<VarDecl>();
610     if (!Var) {
611       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
612       continue;
613     }
614 
615     // Ignore invalid decls; they'll just confuse the code later.
616     if (Var->isInvalidDecl())
617       continue;
618 
619     if (!Var->hasLocalStorage()) {
620       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
621       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
622       continue;
623     }
624 
625     // C++11 [expr.prim.lambda]p8:
626     //   An identifier or this shall not appear more than once in a
627     //   lambda-capture.
628     if (LSI->isCaptured(Var)) {
629       Diag(C->Loc, diag::err_capture_more_than_once)
630         << C->Id
631         << SourceRange(LSI->getCapture(Var).getLocation())
632         << FixItHint::CreateRemoval(
633              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
634       continue;
635     }
636 
637     // C++11 [expr.prim.lambda]p23:
638     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
639     SourceLocation EllipsisLoc;
640     if (C->EllipsisLoc.isValid()) {
641       if (Var->isParameterPack()) {
642         EllipsisLoc = C->EllipsisLoc;
643       } else {
644         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
645           << SourceRange(C->Loc);
646 
647         // Just ignore the ellipsis.
648       }
649     } else if (Var->isParameterPack()) {
650       ContainsUnexpandedParameterPack = true;
651     }
652 
653     TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
654                                                  TryCapture_ExplicitByVal;
655     tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
656   }
657   finishLambdaExplicitCaptures(LSI);
658 
659   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
660 
661   // Add lambda parameters into scope.
662   addLambdaParameters(Method, CurScope);
663 
664   // Enter a new evaluation context to insulate the lambda from any
665   // cleanups from the enclosing full-expression.
666   PushExpressionEvaluationContext(PotentiallyEvaluated);
667 }
668 
669 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
670                             bool IsInstantiation) {
671   // Leave the expression-evaluation context.
672   DiscardCleanupsInEvaluationContext();
673   PopExpressionEvaluationContext();
674 
675   // Leave the context of the lambda.
676   if (!IsInstantiation)
677     PopDeclContext();
678 
679   // Finalize the lambda.
680   LambdaScopeInfo *LSI = getCurLambda();
681   CXXRecordDecl *Class = LSI->Lambda;
682   Class->setInvalidDecl();
683   SmallVector<Decl*, 4> Fields;
684   for (RecordDecl::field_iterator i = Class->field_begin(),
685                                   e = Class->field_end(); i != e; ++i)
686     Fields.push_back(*i);
687   ActOnFields(0, Class->getLocation(), Class, Fields,
688               SourceLocation(), SourceLocation(), 0);
689   CheckCompletedCXXClass(Class);
690 
691   PopFunctionScopeInfo();
692 }
693 
694 /// \brief Add a lambda's conversion to function pointer, as described in
695 /// C++11 [expr.prim.lambda]p6.
696 static void addFunctionPointerConversion(Sema &S,
697                                          SourceRange IntroducerRange,
698                                          CXXRecordDecl *Class,
699                                          CXXMethodDecl *CallOperator) {
700   // Add the conversion to function pointer.
701   const FunctionProtoType *Proto
702     = CallOperator->getType()->getAs<FunctionProtoType>();
703   QualType FunctionPtrTy;
704   QualType FunctionTy;
705   {
706     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
707     ExtInfo.TypeQuals = 0;
708     FunctionTy =
709       S.Context.getFunctionType(Proto->getResultType(),
710                                 ArrayRef<QualType>(Proto->arg_type_begin(),
711                                                    Proto->getNumArgs()),
712                                 ExtInfo);
713     FunctionPtrTy = S.Context.getPointerType(FunctionTy);
714   }
715 
716   FunctionProtoType::ExtProtoInfo ExtInfo;
717   ExtInfo.TypeQuals = Qualifiers::Const;
718   QualType ConvTy =
719     S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
720 
721   SourceLocation Loc = IntroducerRange.getBegin();
722   DeclarationName Name
723     = S.Context.DeclarationNames.getCXXConversionFunctionName(
724         S.Context.getCanonicalType(FunctionPtrTy));
725   DeclarationNameLoc NameLoc;
726   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
727                                                                Loc);
728   CXXConversionDecl *Conversion
729     = CXXConversionDecl::Create(S.Context, Class, Loc,
730                                 DeclarationNameInfo(Name, Loc, NameLoc),
731                                 ConvTy,
732                                 S.Context.getTrivialTypeSourceInfo(ConvTy,
733                                                                    Loc),
734                                 /*isInline=*/false, /*isExplicit=*/false,
735                                 /*isConstexpr=*/false,
736                                 CallOperator->getBody()->getLocEnd());
737   Conversion->setAccess(AS_public);
738   Conversion->setImplicit(true);
739   Class->addDecl(Conversion);
740 
741   // Add a non-static member function "__invoke" that will be the result of
742   // the conversion.
743   Name = &S.Context.Idents.get("__invoke");
744   CXXMethodDecl *Invoke
745     = CXXMethodDecl::Create(S.Context, Class, Loc,
746                             DeclarationNameInfo(Name, Loc), FunctionTy,
747                             CallOperator->getTypeSourceInfo(),
748                             SC_Static, /*IsInline=*/true,
749                             /*IsConstexpr=*/false,
750                             CallOperator->getBody()->getLocEnd());
751   SmallVector<ParmVarDecl *, 4> InvokeParams;
752   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
753     ParmVarDecl *From = CallOperator->getParamDecl(I);
754     InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
755                                                From->getLocStart(),
756                                                From->getLocation(),
757                                                From->getIdentifier(),
758                                                From->getType(),
759                                                From->getTypeSourceInfo(),
760                                                From->getStorageClass(),
761                                                /*DefaultArg=*/0));
762   }
763   Invoke->setParams(InvokeParams);
764   Invoke->setAccess(AS_private);
765   Invoke->setImplicit(true);
766   Class->addDecl(Invoke);
767 }
768 
769 /// \brief Add a lambda's conversion to block pointer.
770 static void addBlockPointerConversion(Sema &S,
771                                       SourceRange IntroducerRange,
772                                       CXXRecordDecl *Class,
773                                       CXXMethodDecl *CallOperator) {
774   const FunctionProtoType *Proto
775     = CallOperator->getType()->getAs<FunctionProtoType>();
776   QualType BlockPtrTy;
777   {
778     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
779     ExtInfo.TypeQuals = 0;
780     QualType FunctionTy
781       = S.Context.getFunctionType(Proto->getResultType(),
782                                   ArrayRef<QualType>(Proto->arg_type_begin(),
783                                                      Proto->getNumArgs()),
784                                   ExtInfo);
785     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
786   }
787 
788   FunctionProtoType::ExtProtoInfo ExtInfo;
789   ExtInfo.TypeQuals = Qualifiers::Const;
790   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
791 
792   SourceLocation Loc = IntroducerRange.getBegin();
793   DeclarationName Name
794     = S.Context.DeclarationNames.getCXXConversionFunctionName(
795         S.Context.getCanonicalType(BlockPtrTy));
796   DeclarationNameLoc NameLoc;
797   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
798   CXXConversionDecl *Conversion
799     = CXXConversionDecl::Create(S.Context, Class, Loc,
800                                 DeclarationNameInfo(Name, Loc, NameLoc),
801                                 ConvTy,
802                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
803                                 /*isInline=*/false, /*isExplicit=*/false,
804                                 /*isConstexpr=*/false,
805                                 CallOperator->getBody()->getLocEnd());
806   Conversion->setAccess(AS_public);
807   Conversion->setImplicit(true);
808   Class->addDecl(Conversion);
809 }
810 
811 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
812                                  Scope *CurScope,
813                                  bool IsInstantiation) {
814   // Collect information from the lambda scope.
815   SmallVector<LambdaExpr::Capture, 4> Captures;
816   SmallVector<Expr *, 4> CaptureInits;
817   LambdaCaptureDefault CaptureDefault;
818   CXXRecordDecl *Class;
819   CXXMethodDecl *CallOperator;
820   SourceRange IntroducerRange;
821   bool ExplicitParams;
822   bool ExplicitResultType;
823   bool LambdaExprNeedsCleanups;
824   bool ContainsUnexpandedParameterPack;
825   SmallVector<VarDecl *, 4> ArrayIndexVars;
826   SmallVector<unsigned, 4> ArrayIndexStarts;
827   {
828     LambdaScopeInfo *LSI = getCurLambda();
829     CallOperator = LSI->CallOperator;
830     Class = LSI->Lambda;
831     IntroducerRange = LSI->IntroducerRange;
832     ExplicitParams = LSI->ExplicitParams;
833     ExplicitResultType = !LSI->HasImplicitReturnType;
834     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
835     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
836     ArrayIndexVars.swap(LSI->ArrayIndexVars);
837     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
838 
839     // Translate captures.
840     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
841       LambdaScopeInfo::Capture From = LSI->Captures[I];
842       assert(!From.isBlockCapture() && "Cannot capture __block variables");
843       bool IsImplicit = I >= LSI->NumExplicitCaptures;
844 
845       // Handle 'this' capture.
846       if (From.isThisCapture()) {
847         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
848                                                IsImplicit,
849                                                LCK_This));
850         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
851                                                          getCurrentThisType(),
852                                                          /*isImplicit=*/true));
853         continue;
854       }
855 
856       VarDecl *Var = From.getVariable();
857       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
858       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
859                                              Kind, Var, From.getEllipsisLoc()));
860       CaptureInits.push_back(From.getCopyExpr());
861     }
862 
863     switch (LSI->ImpCaptureStyle) {
864     case CapturingScopeInfo::ImpCap_None:
865       CaptureDefault = LCD_None;
866       break;
867 
868     case CapturingScopeInfo::ImpCap_LambdaByval:
869       CaptureDefault = LCD_ByCopy;
870       break;
871 
872     case CapturingScopeInfo::ImpCap_CapturedRegion:
873     case CapturingScopeInfo::ImpCap_LambdaByref:
874       CaptureDefault = LCD_ByRef;
875       break;
876 
877     case CapturingScopeInfo::ImpCap_Block:
878       llvm_unreachable("block capture in lambda");
879       break;
880     }
881 
882     // C++11 [expr.prim.lambda]p4:
883     //   If a lambda-expression does not include a
884     //   trailing-return-type, it is as if the trailing-return-type
885     //   denotes the following type:
886     // FIXME: Assumes current resolution to core issue 975.
887     if (LSI->HasImplicitReturnType) {
888       deduceClosureReturnType(*LSI);
889 
890       //   - if there are no return statements in the
891       //     compound-statement, or all return statements return
892       //     either an expression of type void or no expression or
893       //     braced-init-list, the type void;
894       if (LSI->ReturnType.isNull()) {
895         LSI->ReturnType = Context.VoidTy;
896       }
897 
898       // Create a function type with the inferred return type.
899       const FunctionProtoType *Proto
900         = CallOperator->getType()->getAs<FunctionProtoType>();
901       QualType FunctionTy
902         = Context.getFunctionType(LSI->ReturnType,
903                                   ArrayRef<QualType>(Proto->arg_type_begin(),
904                                                      Proto->getNumArgs()),
905                                   Proto->getExtProtoInfo());
906       CallOperator->setType(FunctionTy);
907     }
908 
909     // C++ [expr.prim.lambda]p7:
910     //   The lambda-expression's compound-statement yields the
911     //   function-body (8.4) of the function call operator [...].
912     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
913     CallOperator->setLexicalDeclContext(Class);
914     Class->addDecl(CallOperator);
915     PopExpressionEvaluationContext();
916 
917     // C++11 [expr.prim.lambda]p6:
918     //   The closure type for a lambda-expression with no lambda-capture
919     //   has a public non-virtual non-explicit const conversion function
920     //   to pointer to function having the same parameter and return
921     //   types as the closure type's function call operator.
922     if (Captures.empty() && CaptureDefault == LCD_None)
923       addFunctionPointerConversion(*this, IntroducerRange, Class,
924                                    CallOperator);
925 
926     // Objective-C++:
927     //   The closure type for a lambda-expression has a public non-virtual
928     //   non-explicit const conversion function to a block pointer having the
929     //   same parameter and return types as the closure type's function call
930     //   operator.
931     if (getLangOpts().Blocks && getLangOpts().ObjC1)
932       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
933 
934     // Finalize the lambda class.
935     SmallVector<Decl*, 4> Fields;
936     for (RecordDecl::field_iterator i = Class->field_begin(),
937                                     e = Class->field_end(); i != e; ++i)
938       Fields.push_back(*i);
939     ActOnFields(0, Class->getLocation(), Class, Fields,
940                 SourceLocation(), SourceLocation(), 0);
941     CheckCompletedCXXClass(Class);
942   }
943 
944   if (LambdaExprNeedsCleanups)
945     ExprNeedsCleanups = true;
946 
947   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
948                                           CaptureDefault, Captures,
949                                           ExplicitParams, ExplicitResultType,
950                                           CaptureInits, ArrayIndexVars,
951                                           ArrayIndexStarts, Body->getLocEnd(),
952                                           ContainsUnexpandedParameterPack);
953 
954   // C++11 [expr.prim.lambda]p2:
955   //   A lambda-expression shall not appear in an unevaluated operand
956   //   (Clause 5).
957   if (!CurContext->isDependentContext()) {
958     switch (ExprEvalContexts.back().Context) {
959     case Unevaluated:
960     case UnevaluatedAbstract:
961       // We don't actually diagnose this case immediately, because we
962       // could be within a context where we might find out later that
963       // the expression is potentially evaluated (e.g., for typeid).
964       ExprEvalContexts.back().Lambdas.push_back(Lambda);
965       break;
966 
967     case ConstantEvaluated:
968     case PotentiallyEvaluated:
969     case PotentiallyEvaluatedIfUsed:
970       break;
971     }
972   }
973 
974   return MaybeBindToTemporary(Lambda);
975 }
976 
977 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
978                                                SourceLocation ConvLocation,
979                                                CXXConversionDecl *Conv,
980                                                Expr *Src) {
981   // Make sure that the lambda call operator is marked used.
982   CXXRecordDecl *Lambda = Conv->getParent();
983   CXXMethodDecl *CallOperator
984     = cast<CXXMethodDecl>(
985         Lambda->lookup(
986           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
987   CallOperator->setReferenced();
988   CallOperator->setUsed();
989 
990   ExprResult Init = PerformCopyInitialization(
991                       InitializedEntity::InitializeBlock(ConvLocation,
992                                                          Src->getType(),
993                                                          /*NRVO=*/false),
994                       CurrentLocation, Src);
995   if (!Init.isInvalid())
996     Init = ActOnFinishFullExpr(Init.take());
997 
998   if (Init.isInvalid())
999     return ExprError();
1000 
1001   // Create the new block to be returned.
1002   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1003 
1004   // Set the type information.
1005   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1006   Block->setIsVariadic(CallOperator->isVariadic());
1007   Block->setBlockMissingReturnType(false);
1008 
1009   // Add parameters.
1010   SmallVector<ParmVarDecl *, 4> BlockParams;
1011   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1012     ParmVarDecl *From = CallOperator->getParamDecl(I);
1013     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1014                                               From->getLocStart(),
1015                                               From->getLocation(),
1016                                               From->getIdentifier(),
1017                                               From->getType(),
1018                                               From->getTypeSourceInfo(),
1019                                               From->getStorageClass(),
1020                                               /*DefaultArg=*/0));
1021   }
1022   Block->setParams(BlockParams);
1023 
1024   Block->setIsConversionFromLambda(true);
1025 
1026   // Add capture. The capture uses a fake variable, which doesn't correspond
1027   // to any actual memory location. However, the initializer copy-initializes
1028   // the lambda object.
1029   TypeSourceInfo *CapVarTSI =
1030       Context.getTrivialTypeSourceInfo(Src->getType());
1031   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1032                                     ConvLocation, 0,
1033                                     Src->getType(), CapVarTSI,
1034                                     SC_None);
1035   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1036                              /*Nested=*/false, /*Copy=*/Init.take());
1037   Block->setCaptures(Context, &Capture, &Capture + 1,
1038                      /*CapturesCXXThis=*/false);
1039 
1040   // Add a fake function body to the block. IR generation is responsible
1041   // for filling in the actual body, which cannot be expressed as an AST.
1042   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1043 
1044   // Create the block literal expression.
1045   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1046   ExprCleanupObjects.push_back(Block);
1047   ExprNeedsCleanups = true;
1048 
1049   return BuildBlock;
1050 }
1051