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 only see integral conversions in valid enumerator-like
279     // expressions.
280     if (ICE->getCastKind() == CK_IntegralCast)
281       return findEnumForBlockReturn(ICE->getSubExpr());
282     return 0;
283   }
284 
285   //   - it is an expression of that formal enum type.
286   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
287     return ET->getDecl();
288   }
289 
290   // Otherwise, nope.
291   return 0;
292 }
293 
294 /// Attempt to find a type T for which the returned expression of the
295 /// given statement is an enumerator-like expression of that type.
296 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
297   if (Expr *retValue = ret->getRetValue())
298     return findEnumForBlockReturn(retValue);
299   return 0;
300 }
301 
302 /// Attempt to find a common type T for which all of the returned
303 /// expressions in a block are enumerator-like expressions of that
304 /// type.
305 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
306   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
307 
308   // Try to find one for the first return.
309   EnumDecl *ED = findEnumForBlockReturn(*i);
310   if (!ED) return 0;
311 
312   // Check that the rest of the returns have the same enum.
313   for (++i; i != e; ++i) {
314     if (findEnumForBlockReturn(*i) != ED)
315       return 0;
316   }
317 
318   // Never infer an anonymous enum type.
319   if (!ED->hasNameForLinkage()) return 0;
320 
321   return ED;
322 }
323 
324 /// Adjust the given return statements so that they formally return
325 /// the given type.  It should require, at most, an IntegralCast.
326 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
327                                      QualType returnType) {
328   for (ArrayRef<ReturnStmt*>::iterator
329          i = returns.begin(), e = returns.end(); i != e; ++i) {
330     ReturnStmt *ret = *i;
331     Expr *retValue = ret->getRetValue();
332     if (S.Context.hasSameType(retValue->getType(), returnType))
333       continue;
334 
335     // Right now we only support integral fixup casts.
336     assert(returnType->isIntegralOrUnscopedEnumerationType());
337     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
338 
339     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
340 
341     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
342     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
343                                  E, /*base path*/ 0, VK_RValue);
344     if (cleanups) {
345       cleanups->setSubExpr(E);
346     } else {
347       ret->setRetValue(E);
348     }
349   }
350 }
351 
352 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
353   assert(CSI.HasImplicitReturnType);
354 
355   // C++ Core Issue #975, proposed resolution:
356   //   If a lambda-expression does not include a trailing-return-type,
357   //   it is as if the trailing-return-type denotes the following type:
358   //     - if there are no return statements in the compound-statement,
359   //       or all return statements return either an expression of type
360   //       void or no expression or braced-init-list, the type void;
361   //     - otherwise, if all return statements return an expression
362   //       and the types of the returned expressions after
363   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
364   //       array-to-pointer conversion (4.2 [conv.array]), and
365   //       function-to-pointer conversion (4.3 [conv.func]) are the
366   //       same, that common type;
367   //     - otherwise, the program is ill-formed.
368   //
369   // In addition, in blocks in non-C++ modes, if all of the return
370   // statements are enumerator-like expressions of some type T, where
371   // T has a name for linkage, then we infer the return type of the
372   // block to be that type.
373 
374   // First case: no return statements, implicit void return type.
375   ASTContext &Ctx = getASTContext();
376   if (CSI.Returns.empty()) {
377     // It's possible there were simply no /valid/ return statements.
378     // In this case, the first one we found may have at least given us a type.
379     if (CSI.ReturnType.isNull())
380       CSI.ReturnType = Ctx.VoidTy;
381     return;
382   }
383 
384   // Second case: at least one return statement has dependent type.
385   // Delay type checking until instantiation.
386   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
387   if (CSI.ReturnType->isDependentType())
388     return;
389 
390   // Try to apply the enum-fuzz rule.
391   if (!getLangOpts().CPlusPlus) {
392     assert(isa<BlockScopeInfo>(CSI));
393     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
394     if (ED) {
395       CSI.ReturnType = Context.getTypeDeclType(ED);
396       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
397       return;
398     }
399   }
400 
401   // Third case: only one return statement. Don't bother doing extra work!
402   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
403                                          E = CSI.Returns.end();
404   if (I+1 == E)
405     return;
406 
407   // General case: many return statements.
408   // Check that they all have compatible return types.
409 
410   // We require the return types to strictly match here.
411   // Note that we've already done the required promotions as part of
412   // processing the return statement.
413   for (; I != E; ++I) {
414     const ReturnStmt *RS = *I;
415     const Expr *RetE = RS->getRetValue();
416 
417     QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
418     if (Context.hasSameType(ReturnType, CSI.ReturnType))
419       continue;
420 
421     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
422     // TODO: It's possible that the *first* return is the divergent one.
423     Diag(RS->getLocStart(),
424          diag::err_typecheck_missing_return_type_incompatible)
425       << ReturnType << CSI.ReturnType
426       << isa<LambdaScopeInfo>(CSI);
427     // Continue iterating so that we keep emitting diagnostics.
428   }
429 }
430 
431 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
432                                         Declarator &ParamInfo,
433                                         Scope *CurScope) {
434   // Determine if we're within a context where we know that the lambda will
435   // be dependent, because there are template parameters in scope.
436   bool KnownDependent = false;
437   if (Scope *TmplScope = CurScope->getTemplateParamParent())
438     if (!TmplScope->decl_empty())
439       KnownDependent = true;
440 
441   // Determine the signature of the call operator.
442   TypeSourceInfo *MethodTyInfo;
443   bool ExplicitParams = true;
444   bool ExplicitResultType = true;
445   bool ContainsUnexpandedParameterPack = false;
446   SourceLocation EndLoc;
447   SmallVector<ParmVarDecl *, 8> Params;
448   if (ParamInfo.getNumTypeObjects() == 0) {
449     // C++11 [expr.prim.lambda]p4:
450     //   If a lambda-expression does not include a lambda-declarator, it is as
451     //   if the lambda-declarator were ().
452     FunctionProtoType::ExtProtoInfo EPI;
453     EPI.HasTrailingReturn = true;
454     EPI.TypeQuals |= DeclSpec::TQ_const;
455     QualType MethodTy = Context.getFunctionType(Context.DependentTy,
456                                                 ArrayRef<QualType>(),
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     assert(C->Id && "missing identifier for capture");
563 
564     // C++11 [expr.prim.lambda]p8:
565     //   If a lambda-capture includes a capture-default that is &, the
566     //   identifiers in the lambda-capture shall not be preceded by &.
567     //   If a lambda-capture includes a capture-default that is =, [...]
568     //   each identifier it contains shall be preceded by &.
569     if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
570       Diag(C->Loc, diag::err_reference_capture_with_reference_default)
571         << FixItHint::CreateRemoval(
572              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
573       continue;
574     } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
575       Diag(C->Loc, diag::err_copy_capture_with_copy_default)
576         << FixItHint::CreateRemoval(
577              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
578       continue;
579     }
580 
581     DeclarationNameInfo Name(C->Id, C->Loc);
582     LookupResult R(*this, Name, LookupOrdinaryName);
583     LookupName(R, CurScope);
584     if (R.isAmbiguous())
585       continue;
586     if (R.empty()) {
587       // FIXME: Disable corrections that would add qualification?
588       CXXScopeSpec ScopeSpec;
589       DeclFilterCCC<VarDecl> Validator;
590       if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
591         continue;
592     }
593 
594     // C++11 [expr.prim.lambda]p10:
595     //   The identifiers in a capture-list are looked up using the usual rules
596     //   for unqualified name lookup (3.4.1); each such lookup shall find a
597     //   variable with automatic storage duration declared in the reaching
598     //   scope of the local lambda expression.
599     //
600     // Note that the 'reaching scope' check happens in tryCaptureVariable().
601     VarDecl *Var = R.getAsSingle<VarDecl>();
602     if (!Var) {
603       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
604       continue;
605     }
606 
607     // Ignore invalid decls; they'll just confuse the code later.
608     if (Var->isInvalidDecl())
609       continue;
610 
611     if (!Var->hasLocalStorage()) {
612       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
613       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
614       continue;
615     }
616 
617     // C++11 [expr.prim.lambda]p8:
618     //   An identifier or this shall not appear more than once in a
619     //   lambda-capture.
620     if (LSI->isCaptured(Var)) {
621       Diag(C->Loc, diag::err_capture_more_than_once)
622         << C->Id
623         << SourceRange(LSI->getCapture(Var).getLocation())
624         << FixItHint::CreateRemoval(
625              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
626       continue;
627     }
628 
629     // C++11 [expr.prim.lambda]p23:
630     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
631     SourceLocation EllipsisLoc;
632     if (C->EllipsisLoc.isValid()) {
633       if (Var->isParameterPack()) {
634         EllipsisLoc = C->EllipsisLoc;
635       } else {
636         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
637           << SourceRange(C->Loc);
638 
639         // Just ignore the ellipsis.
640       }
641     } else if (Var->isParameterPack()) {
642       ContainsUnexpandedParameterPack = true;
643     }
644 
645     TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
646                                                  TryCapture_ExplicitByVal;
647     tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
648   }
649   finishLambdaExplicitCaptures(LSI);
650 
651   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
652 
653   // Add lambda parameters into scope.
654   addLambdaParameters(Method, CurScope);
655 
656   // Enter a new evaluation context to insulate the lambda from any
657   // cleanups from the enclosing full-expression.
658   PushExpressionEvaluationContext(PotentiallyEvaluated);
659 }
660 
661 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
662                             bool IsInstantiation) {
663   // Leave the expression-evaluation context.
664   DiscardCleanupsInEvaluationContext();
665   PopExpressionEvaluationContext();
666 
667   // Leave the context of the lambda.
668   if (!IsInstantiation)
669     PopDeclContext();
670 
671   // Finalize the lambda.
672   LambdaScopeInfo *LSI = getCurLambda();
673   CXXRecordDecl *Class = LSI->Lambda;
674   Class->setInvalidDecl();
675   SmallVector<Decl*, 4> Fields;
676   for (RecordDecl::field_iterator i = Class->field_begin(),
677                                   e = Class->field_end(); i != e; ++i)
678     Fields.push_back(*i);
679   ActOnFields(0, Class->getLocation(), Class, Fields,
680               SourceLocation(), SourceLocation(), 0);
681   CheckCompletedCXXClass(Class);
682 
683   PopFunctionScopeInfo();
684 }
685 
686 /// \brief Add a lambda's conversion to function pointer, as described in
687 /// C++11 [expr.prim.lambda]p6.
688 static void addFunctionPointerConversion(Sema &S,
689                                          SourceRange IntroducerRange,
690                                          CXXRecordDecl *Class,
691                                          CXXMethodDecl *CallOperator) {
692   // Add the conversion to function pointer.
693   const FunctionProtoType *Proto
694     = CallOperator->getType()->getAs<FunctionProtoType>();
695   QualType FunctionPtrTy;
696   QualType FunctionTy;
697   {
698     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
699     ExtInfo.TypeQuals = 0;
700     FunctionTy =
701       S.Context.getFunctionType(Proto->getResultType(),
702                                 ArrayRef<QualType>(Proto->arg_type_begin(),
703                                                    Proto->getNumArgs()),
704                                 ExtInfo);
705     FunctionPtrTy = S.Context.getPointerType(FunctionTy);
706   }
707 
708   FunctionProtoType::ExtProtoInfo ExtInfo;
709   ExtInfo.TypeQuals = Qualifiers::Const;
710   QualType ConvTy =
711     S.Context.getFunctionType(FunctionPtrTy, ArrayRef<QualType>(), ExtInfo);
712 
713   SourceLocation Loc = IntroducerRange.getBegin();
714   DeclarationName Name
715     = S.Context.DeclarationNames.getCXXConversionFunctionName(
716         S.Context.getCanonicalType(FunctionPtrTy));
717   DeclarationNameLoc NameLoc;
718   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
719                                                                Loc);
720   CXXConversionDecl *Conversion
721     = CXXConversionDecl::Create(S.Context, Class, Loc,
722                                 DeclarationNameInfo(Name, Loc, NameLoc),
723                                 ConvTy,
724                                 S.Context.getTrivialTypeSourceInfo(ConvTy,
725                                                                    Loc),
726                                 /*isInline=*/false, /*isExplicit=*/false,
727                                 /*isConstexpr=*/false,
728                                 CallOperator->getBody()->getLocEnd());
729   Conversion->setAccess(AS_public);
730   Conversion->setImplicit(true);
731   Class->addDecl(Conversion);
732 
733   // Add a non-static member function "__invoke" that will be the result of
734   // the conversion.
735   Name = &S.Context.Idents.get("__invoke");
736   CXXMethodDecl *Invoke
737     = CXXMethodDecl::Create(S.Context, Class, Loc,
738                             DeclarationNameInfo(Name, Loc), FunctionTy,
739                             CallOperator->getTypeSourceInfo(),
740                             SC_Static, /*IsInline=*/true,
741                             /*IsConstexpr=*/false,
742                             CallOperator->getBody()->getLocEnd());
743   SmallVector<ParmVarDecl *, 4> InvokeParams;
744   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
745     ParmVarDecl *From = CallOperator->getParamDecl(I);
746     InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
747                                                From->getLocStart(),
748                                                From->getLocation(),
749                                                From->getIdentifier(),
750                                                From->getType(),
751                                                From->getTypeSourceInfo(),
752                                                From->getStorageClass(),
753                                                /*DefaultArg=*/0));
754   }
755   Invoke->setParams(InvokeParams);
756   Invoke->setAccess(AS_private);
757   Invoke->setImplicit(true);
758   Class->addDecl(Invoke);
759 }
760 
761 /// \brief Add a lambda's conversion to block pointer.
762 static void addBlockPointerConversion(Sema &S,
763                                       SourceRange IntroducerRange,
764                                       CXXRecordDecl *Class,
765                                       CXXMethodDecl *CallOperator) {
766   const FunctionProtoType *Proto
767     = CallOperator->getType()->getAs<FunctionProtoType>();
768   QualType BlockPtrTy;
769   {
770     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
771     ExtInfo.TypeQuals = 0;
772     QualType FunctionTy
773       = S.Context.getFunctionType(Proto->getResultType(),
774                                   ArrayRef<QualType>(Proto->arg_type_begin(),
775                                                      Proto->getNumArgs()),
776                                   ExtInfo);
777     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
778   }
779 
780   FunctionProtoType::ExtProtoInfo ExtInfo;
781   ExtInfo.TypeQuals = Qualifiers::Const;
782   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, ArrayRef<QualType>(),
783                                               ExtInfo);
784 
785   SourceLocation Loc = IntroducerRange.getBegin();
786   DeclarationName Name
787     = S.Context.DeclarationNames.getCXXConversionFunctionName(
788         S.Context.getCanonicalType(BlockPtrTy));
789   DeclarationNameLoc NameLoc;
790   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
791   CXXConversionDecl *Conversion
792     = CXXConversionDecl::Create(S.Context, Class, Loc,
793                                 DeclarationNameInfo(Name, Loc, NameLoc),
794                                 ConvTy,
795                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
796                                 /*isInline=*/false, /*isExplicit=*/false,
797                                 /*isConstexpr=*/false,
798                                 CallOperator->getBody()->getLocEnd());
799   Conversion->setAccess(AS_public);
800   Conversion->setImplicit(true);
801   Class->addDecl(Conversion);
802 }
803 
804 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
805                                  Scope *CurScope,
806                                  bool IsInstantiation) {
807   // Collect information from the lambda scope.
808   SmallVector<LambdaExpr::Capture, 4> Captures;
809   SmallVector<Expr *, 4> CaptureInits;
810   LambdaCaptureDefault CaptureDefault;
811   CXXRecordDecl *Class;
812   CXXMethodDecl *CallOperator;
813   SourceRange IntroducerRange;
814   bool ExplicitParams;
815   bool ExplicitResultType;
816   bool LambdaExprNeedsCleanups;
817   bool ContainsUnexpandedParameterPack;
818   SmallVector<VarDecl *, 4> ArrayIndexVars;
819   SmallVector<unsigned, 4> ArrayIndexStarts;
820   {
821     LambdaScopeInfo *LSI = getCurLambda();
822     CallOperator = LSI->CallOperator;
823     Class = LSI->Lambda;
824     IntroducerRange = LSI->IntroducerRange;
825     ExplicitParams = LSI->ExplicitParams;
826     ExplicitResultType = !LSI->HasImplicitReturnType;
827     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
828     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
829     ArrayIndexVars.swap(LSI->ArrayIndexVars);
830     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
831 
832     // Translate captures.
833     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
834       LambdaScopeInfo::Capture From = LSI->Captures[I];
835       assert(!From.isBlockCapture() && "Cannot capture __block variables");
836       bool IsImplicit = I >= LSI->NumExplicitCaptures;
837 
838       // Handle 'this' capture.
839       if (From.isThisCapture()) {
840         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
841                                                IsImplicit,
842                                                LCK_This));
843         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
844                                                          getCurrentThisType(),
845                                                          /*isImplicit=*/true));
846         continue;
847       }
848 
849       VarDecl *Var = From.getVariable();
850       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
851       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
852                                              Kind, Var, From.getEllipsisLoc()));
853       CaptureInits.push_back(From.getCopyExpr());
854     }
855 
856     switch (LSI->ImpCaptureStyle) {
857     case CapturingScopeInfo::ImpCap_None:
858       CaptureDefault = LCD_None;
859       break;
860 
861     case CapturingScopeInfo::ImpCap_LambdaByval:
862       CaptureDefault = LCD_ByCopy;
863       break;
864 
865     case CapturingScopeInfo::ImpCap_CapturedRegion:
866     case CapturingScopeInfo::ImpCap_LambdaByref:
867       CaptureDefault = LCD_ByRef;
868       break;
869 
870     case CapturingScopeInfo::ImpCap_Block:
871       llvm_unreachable("block capture in lambda");
872       break;
873     }
874 
875     // C++11 [expr.prim.lambda]p4:
876     //   If a lambda-expression does not include a
877     //   trailing-return-type, it is as if the trailing-return-type
878     //   denotes the following type:
879     // FIXME: Assumes current resolution to core issue 975.
880     if (LSI->HasImplicitReturnType) {
881       deduceClosureReturnType(*LSI);
882 
883       //   - if there are no return statements in the
884       //     compound-statement, or all return statements return
885       //     either an expression of type void or no expression or
886       //     braced-init-list, the type void;
887       if (LSI->ReturnType.isNull()) {
888         LSI->ReturnType = Context.VoidTy;
889       }
890 
891       // Create a function type with the inferred return type.
892       const FunctionProtoType *Proto
893         = CallOperator->getType()->getAs<FunctionProtoType>();
894       QualType FunctionTy
895         = Context.getFunctionType(LSI->ReturnType,
896                                   ArrayRef<QualType>(Proto->arg_type_begin(),
897                                                      Proto->getNumArgs()),
898                                   Proto->getExtProtoInfo());
899       CallOperator->setType(FunctionTy);
900     }
901 
902     // C++ [expr.prim.lambda]p7:
903     //   The lambda-expression's compound-statement yields the
904     //   function-body (8.4) of the function call operator [...].
905     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
906     CallOperator->setLexicalDeclContext(Class);
907     Class->addDecl(CallOperator);
908     PopExpressionEvaluationContext();
909 
910     // C++11 [expr.prim.lambda]p6:
911     //   The closure type for a lambda-expression with no lambda-capture
912     //   has a public non-virtual non-explicit const conversion function
913     //   to pointer to function having the same parameter and return
914     //   types as the closure type's function call operator.
915     if (Captures.empty() && CaptureDefault == LCD_None)
916       addFunctionPointerConversion(*this, IntroducerRange, Class,
917                                    CallOperator);
918 
919     // Objective-C++:
920     //   The closure type for a lambda-expression has a public non-virtual
921     //   non-explicit const conversion function to a block pointer having the
922     //   same parameter and return types as the closure type's function call
923     //   operator.
924     if (getLangOpts().Blocks && getLangOpts().ObjC1)
925       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
926 
927     // Finalize the lambda class.
928     SmallVector<Decl*, 4> Fields;
929     for (RecordDecl::field_iterator i = Class->field_begin(),
930                                     e = Class->field_end(); i != e; ++i)
931       Fields.push_back(*i);
932     ActOnFields(0, Class->getLocation(), Class, Fields,
933                 SourceLocation(), SourceLocation(), 0);
934     CheckCompletedCXXClass(Class);
935   }
936 
937   if (LambdaExprNeedsCleanups)
938     ExprNeedsCleanups = true;
939 
940   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
941                                           CaptureDefault, Captures,
942                                           ExplicitParams, ExplicitResultType,
943                                           CaptureInits, ArrayIndexVars,
944                                           ArrayIndexStarts, Body->getLocEnd(),
945                                           ContainsUnexpandedParameterPack);
946 
947   // C++11 [expr.prim.lambda]p2:
948   //   A lambda-expression shall not appear in an unevaluated operand
949   //   (Clause 5).
950   if (!CurContext->isDependentContext()) {
951     switch (ExprEvalContexts.back().Context) {
952     case Unevaluated:
953       // We don't actually diagnose this case immediately, because we
954       // could be within a context where we might find out later that
955       // the expression is potentially evaluated (e.g., for typeid).
956       ExprEvalContexts.back().Lambdas.push_back(Lambda);
957       break;
958 
959     case ConstantEvaluated:
960     case PotentiallyEvaluated:
961     case PotentiallyEvaluatedIfUsed:
962       break;
963     }
964   }
965 
966   return MaybeBindToTemporary(Lambda);
967 }
968 
969 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
970                                                SourceLocation ConvLocation,
971                                                CXXConversionDecl *Conv,
972                                                Expr *Src) {
973   // Make sure that the lambda call operator is marked used.
974   CXXRecordDecl *Lambda = Conv->getParent();
975   CXXMethodDecl *CallOperator
976     = cast<CXXMethodDecl>(
977         Lambda->lookup(
978           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
979   CallOperator->setReferenced();
980   CallOperator->setUsed();
981 
982   ExprResult Init = PerformCopyInitialization(
983                       InitializedEntity::InitializeBlock(ConvLocation,
984                                                          Src->getType(),
985                                                          /*NRVO=*/false),
986                       CurrentLocation, Src);
987   if (!Init.isInvalid())
988     Init = ActOnFinishFullExpr(Init.take());
989 
990   if (Init.isInvalid())
991     return ExprError();
992 
993   // Create the new block to be returned.
994   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
995 
996   // Set the type information.
997   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
998   Block->setIsVariadic(CallOperator->isVariadic());
999   Block->setBlockMissingReturnType(false);
1000 
1001   // Add parameters.
1002   SmallVector<ParmVarDecl *, 4> BlockParams;
1003   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1004     ParmVarDecl *From = CallOperator->getParamDecl(I);
1005     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1006                                               From->getLocStart(),
1007                                               From->getLocation(),
1008                                               From->getIdentifier(),
1009                                               From->getType(),
1010                                               From->getTypeSourceInfo(),
1011                                               From->getStorageClass(),
1012                                               /*DefaultArg=*/0));
1013   }
1014   Block->setParams(BlockParams);
1015 
1016   Block->setIsConversionFromLambda(true);
1017 
1018   // Add capture. The capture uses a fake variable, which doesn't correspond
1019   // to any actual memory location. However, the initializer copy-initializes
1020   // the lambda object.
1021   TypeSourceInfo *CapVarTSI =
1022       Context.getTrivialTypeSourceInfo(Src->getType());
1023   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1024                                     ConvLocation, 0,
1025                                     Src->getType(), CapVarTSI,
1026                                     SC_None);
1027   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1028                              /*Nested=*/false, /*Copy=*/Init.take());
1029   Block->setCaptures(Context, &Capture, &Capture + 1,
1030                      /*CapturesCXXThis=*/false);
1031 
1032   // Add a fake function body to the block. IR generation is responsible
1033   // for filling in the actual body, which cannot be expressed as an AST.
1034   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1035 
1036   // Create the block literal expression.
1037   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1038   ExprCleanupObjects.push_back(Block);
1039   ExprNeedsCleanups = true;
1040 
1041   return BuildBlock;
1042 }
1043