]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaLambda.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / lib / Sema / SemaLambda.cpp
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, None,
456                                                 EPI);
457     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
458     ExplicitParams = false;
459     ExplicitResultType = false;
460     EndLoc = Intro.Range.getEnd();
461   } else {
462     assert(ParamInfo.isFunctionDeclarator() &&
463            "lambda-declarator is a function");
464     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
465     
466     // C++11 [expr.prim.lambda]p5:
467     //   This function call operator is declared const (9.3.1) if and only if 
468     //   the lambda-expression's parameter-declaration-clause is not followed 
469     //   by mutable. It is neither virtual nor declared volatile. [...]
470     if (!FTI.hasMutableQualifier())
471       FTI.TypeQuals |= DeclSpec::TQ_const;
472     
473     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
474     assert(MethodTyInfo && "no type from lambda-declarator");
475     EndLoc = ParamInfo.getSourceRange().getEnd();
476     
477     ExplicitResultType
478       = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType() 
479                                                         != Context.DependentTy;
480
481     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
482         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
483       // Empty arg list, don't push any params.
484       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
485     } else {
486       Params.reserve(FTI.NumArgs);
487       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
488         Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
489     }
490
491     // Check for unexpanded parameter packs in the method type.
492     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
493       ContainsUnexpandedParameterPack = true;
494   }
495
496   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
497                                                  KnownDependent);
498
499   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
500                                                 MethodTyInfo, EndLoc, Params);
501   
502   if (ExplicitParams)
503     CheckCXXDefaultArguments(Method);
504   
505   // Attributes on the lambda apply to the method.  
506   ProcessDeclAttributes(CurScope, Method, ParamInfo);
507   
508   // Introduce the function call operator as the current declaration context.
509   PushDeclContext(CurScope, Method);
510     
511   // Introduce the lambda scope.
512   LambdaScopeInfo *LSI
513     = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
514                        ExplicitResultType,
515                        !Method->isConst());
516  
517   // Handle explicit captures.
518   SourceLocation PrevCaptureLoc
519     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
520   for (SmallVector<LambdaCapture, 4>::const_iterator
521          C = Intro.Captures.begin(), 
522          E = Intro.Captures.end(); 
523        C != E; 
524        PrevCaptureLoc = C->Loc, ++C) {
525     if (C->Kind == LCK_This) {
526       // C++11 [expr.prim.lambda]p8:
527       //   An identifier or this shall not appear more than once in a 
528       //   lambda-capture.
529       if (LSI->isCXXThisCaptured()) {
530         Diag(C->Loc, diag::err_capture_more_than_once) 
531           << "'this'"
532           << SourceRange(LSI->getCXXThisCapture().getLocation())
533           << FixItHint::CreateRemoval(
534                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
535         continue;
536       }
537
538       // C++11 [expr.prim.lambda]p8:
539       //   If a lambda-capture includes a capture-default that is =, the 
540       //   lambda-capture shall not contain this [...].
541       if (Intro.Default == LCD_ByCopy) {
542         Diag(C->Loc, diag::err_this_capture_with_copy_default)
543           << FixItHint::CreateRemoval(
544                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
545         continue;
546       }
547
548       // C++11 [expr.prim.lambda]p12:
549       //   If this is captured by a local lambda expression, its nearest
550       //   enclosing function shall be a non-static member function.
551       QualType ThisCaptureType = getCurrentThisType();
552       if (ThisCaptureType.isNull()) {
553         Diag(C->Loc, diag::err_this_capture) << true;
554         continue;
555       }
556       
557       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
558       continue;
559     }
560
561     assert(C->Id && "missing identifier for capture");
562
563     // C++11 [expr.prim.lambda]p8:
564     //   If a lambda-capture includes a capture-default that is &, the 
565     //   identifiers in the lambda-capture shall not be preceded by &.
566     //   If a lambda-capture includes a capture-default that is =, [...]
567     //   each identifier it contains shall be preceded by &.
568     if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
569       Diag(C->Loc, diag::err_reference_capture_with_reference_default)
570         << FixItHint::CreateRemoval(
571              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
572       continue;
573     } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
574       Diag(C->Loc, diag::err_copy_capture_with_copy_default)
575         << FixItHint::CreateRemoval(
576              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
577       continue;
578     }
579
580     DeclarationNameInfo Name(C->Id, C->Loc);
581     LookupResult R(*this, Name, LookupOrdinaryName);
582     LookupName(R, CurScope);
583     if (R.isAmbiguous())
584       continue;
585     if (R.empty()) {
586       // FIXME: Disable corrections that would add qualification?
587       CXXScopeSpec ScopeSpec;
588       DeclFilterCCC<VarDecl> Validator;
589       if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
590         continue;
591     }
592
593     // C++11 [expr.prim.lambda]p10:
594     //   The identifiers in a capture-list are looked up using the usual rules
595     //   for unqualified name lookup (3.4.1); each such lookup shall find a 
596     //   variable with automatic storage duration declared in the reaching 
597     //   scope of the local lambda expression.
598     // 
599     // Note that the 'reaching scope' check happens in tryCaptureVariable().
600     VarDecl *Var = R.getAsSingle<VarDecl>();
601     if (!Var) {
602       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
603       continue;
604     }
605
606     // Ignore invalid decls; they'll just confuse the code later.
607     if (Var->isInvalidDecl())
608       continue;
609
610     if (!Var->hasLocalStorage()) {
611       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
612       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
613       continue;
614     }
615
616     // C++11 [expr.prim.lambda]p8:
617     //   An identifier or this shall not appear more than once in a 
618     //   lambda-capture.
619     if (LSI->isCaptured(Var)) {
620       Diag(C->Loc, diag::err_capture_more_than_once) 
621         << C->Id
622         << SourceRange(LSI->getCapture(Var).getLocation())
623         << FixItHint::CreateRemoval(
624              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
625       continue;
626     }
627
628     // C++11 [expr.prim.lambda]p23:
629     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
630     SourceLocation EllipsisLoc;
631     if (C->EllipsisLoc.isValid()) {
632       if (Var->isParameterPack()) {
633         EllipsisLoc = C->EllipsisLoc;
634       } else {
635         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636           << SourceRange(C->Loc);
637         
638         // Just ignore the ellipsis.
639       }
640     } else if (Var->isParameterPack()) {
641       ContainsUnexpandedParameterPack = true;
642     }
643     
644     TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
645                                                  TryCapture_ExplicitByVal;
646     tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
647   }
648   finishLambdaExplicitCaptures(LSI);
649
650   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
651
652   // Add lambda parameters into scope.
653   addLambdaParameters(Method, CurScope);
654
655   // Enter a new evaluation context to insulate the lambda from any
656   // cleanups from the enclosing full-expression.
657   PushExpressionEvaluationContext(PotentiallyEvaluated);  
658 }
659
660 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
661                             bool IsInstantiation) {
662   // Leave the expression-evaluation context.
663   DiscardCleanupsInEvaluationContext();
664   PopExpressionEvaluationContext();
665
666   // Leave the context of the lambda.
667   if (!IsInstantiation)
668     PopDeclContext();
669
670   // Finalize the lambda.
671   LambdaScopeInfo *LSI = getCurLambda();
672   CXXRecordDecl *Class = LSI->Lambda;
673   Class->setInvalidDecl();
674   SmallVector<Decl*, 4> Fields;
675   for (RecordDecl::field_iterator i = Class->field_begin(),
676                                   e = Class->field_end(); i != e; ++i)
677     Fields.push_back(*i);
678   ActOnFields(0, Class->getLocation(), Class, Fields, 
679               SourceLocation(), SourceLocation(), 0);
680   CheckCompletedCXXClass(Class);
681
682   PopFunctionScopeInfo();
683 }
684
685 /// \brief Add a lambda's conversion to function pointer, as described in
686 /// C++11 [expr.prim.lambda]p6.
687 static void addFunctionPointerConversion(Sema &S, 
688                                          SourceRange IntroducerRange,
689                                          CXXRecordDecl *Class,
690                                          CXXMethodDecl *CallOperator) {
691   // Add the conversion to function pointer.
692   const FunctionProtoType *Proto
693     = CallOperator->getType()->getAs<FunctionProtoType>(); 
694   QualType FunctionPtrTy;
695   QualType FunctionTy;
696   {
697     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
698     ExtInfo.TypeQuals = 0;
699     FunctionTy =
700       S.Context.getFunctionType(Proto->getResultType(),
701                                 ArrayRef<QualType>(Proto->arg_type_begin(),
702                                                    Proto->getNumArgs()),
703                                 ExtInfo);
704     FunctionPtrTy = S.Context.getPointerType(FunctionTy);
705   }
706   
707   FunctionProtoType::ExtProtoInfo ExtInfo;
708   ExtInfo.TypeQuals = Qualifiers::Const;
709   QualType ConvTy =
710     S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
711   
712   SourceLocation Loc = IntroducerRange.getBegin();
713   DeclarationName Name
714     = S.Context.DeclarationNames.getCXXConversionFunctionName(
715         S.Context.getCanonicalType(FunctionPtrTy));
716   DeclarationNameLoc NameLoc;
717   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
718                                                                Loc);
719   CXXConversionDecl *Conversion 
720     = CXXConversionDecl::Create(S.Context, Class, Loc, 
721                                 DeclarationNameInfo(Name, Loc, NameLoc),
722                                 ConvTy, 
723                                 S.Context.getTrivialTypeSourceInfo(ConvTy, 
724                                                                    Loc),
725                                 /*isInline=*/false, /*isExplicit=*/false,
726                                 /*isConstexpr=*/false, 
727                                 CallOperator->getBody()->getLocEnd());
728   Conversion->setAccess(AS_public);
729   Conversion->setImplicit(true);
730   Class->addDecl(Conversion);
731   
732   // Add a non-static member function "__invoke" that will be the result of
733   // the conversion.
734   Name = &S.Context.Idents.get("__invoke");
735   CXXMethodDecl *Invoke
736     = CXXMethodDecl::Create(S.Context, Class, Loc, 
737                             DeclarationNameInfo(Name, Loc), FunctionTy, 
738                             CallOperator->getTypeSourceInfo(),
739                             SC_Static, /*IsInline=*/true,
740                             /*IsConstexpr=*/false, 
741                             CallOperator->getBody()->getLocEnd());
742   SmallVector<ParmVarDecl *, 4> InvokeParams;
743   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
744     ParmVarDecl *From = CallOperator->getParamDecl(I);
745     InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
746                                                From->getLocStart(),
747                                                From->getLocation(),
748                                                From->getIdentifier(),
749                                                From->getType(),
750                                                From->getTypeSourceInfo(),
751                                                From->getStorageClass(),
752                                                /*DefaultArg=*/0));
753   }
754   Invoke->setParams(InvokeParams);
755   Invoke->setAccess(AS_private);
756   Invoke->setImplicit(true);
757   Class->addDecl(Invoke);
758 }
759
760 /// \brief Add a lambda's conversion to block pointer.
761 static void addBlockPointerConversion(Sema &S, 
762                                       SourceRange IntroducerRange,
763                                       CXXRecordDecl *Class,
764                                       CXXMethodDecl *CallOperator) {
765   const FunctionProtoType *Proto
766     = CallOperator->getType()->getAs<FunctionProtoType>(); 
767   QualType BlockPtrTy;
768   {
769     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
770     ExtInfo.TypeQuals = 0;
771     QualType FunctionTy
772       = S.Context.getFunctionType(Proto->getResultType(),
773                                   ArrayRef<QualType>(Proto->arg_type_begin(),
774                                                      Proto->getNumArgs()),
775                                   ExtInfo);
776     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
777   }
778   
779   FunctionProtoType::ExtProtoInfo ExtInfo;
780   ExtInfo.TypeQuals = Qualifiers::Const;
781   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
782   
783   SourceLocation Loc = IntroducerRange.getBegin();
784   DeclarationName Name
785     = S.Context.DeclarationNames.getCXXConversionFunctionName(
786         S.Context.getCanonicalType(BlockPtrTy));
787   DeclarationNameLoc NameLoc;
788   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
789   CXXConversionDecl *Conversion 
790     = CXXConversionDecl::Create(S.Context, Class, Loc, 
791                                 DeclarationNameInfo(Name, Loc, NameLoc),
792                                 ConvTy, 
793                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
794                                 /*isInline=*/false, /*isExplicit=*/false,
795                                 /*isConstexpr=*/false, 
796                                 CallOperator->getBody()->getLocEnd());
797   Conversion->setAccess(AS_public);
798   Conversion->setImplicit(true);
799   Class->addDecl(Conversion);
800 }
801          
802 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 
803                                  Scope *CurScope, 
804                                  bool IsInstantiation) {
805   // Collect information from the lambda scope.
806   SmallVector<LambdaExpr::Capture, 4> Captures;
807   SmallVector<Expr *, 4> CaptureInits;
808   LambdaCaptureDefault CaptureDefault;
809   CXXRecordDecl *Class;
810   CXXMethodDecl *CallOperator;
811   SourceRange IntroducerRange;
812   bool ExplicitParams;
813   bool ExplicitResultType;
814   bool LambdaExprNeedsCleanups;
815   bool ContainsUnexpandedParameterPack;
816   SmallVector<VarDecl *, 4> ArrayIndexVars;
817   SmallVector<unsigned, 4> ArrayIndexStarts;
818   {
819     LambdaScopeInfo *LSI = getCurLambda();
820     CallOperator = LSI->CallOperator;
821     Class = LSI->Lambda;
822     IntroducerRange = LSI->IntroducerRange;
823     ExplicitParams = LSI->ExplicitParams;
824     ExplicitResultType = !LSI->HasImplicitReturnType;
825     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
826     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
827     ArrayIndexVars.swap(LSI->ArrayIndexVars);
828     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
829     
830     // Translate captures.
831     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
832       LambdaScopeInfo::Capture From = LSI->Captures[I];
833       assert(!From.isBlockCapture() && "Cannot capture __block variables");
834       bool IsImplicit = I >= LSI->NumExplicitCaptures;
835
836       // Handle 'this' capture.
837       if (From.isThisCapture()) {
838         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
839                                                IsImplicit,
840                                                LCK_This));
841         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
842                                                          getCurrentThisType(),
843                                                          /*isImplicit=*/true));
844         continue;
845       }
846
847       VarDecl *Var = From.getVariable();
848       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
849       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit, 
850                                              Kind, Var, From.getEllipsisLoc()));
851       CaptureInits.push_back(From.getCopyExpr());
852     }
853
854     switch (LSI->ImpCaptureStyle) {
855     case CapturingScopeInfo::ImpCap_None:
856       CaptureDefault = LCD_None;
857       break;
858
859     case CapturingScopeInfo::ImpCap_LambdaByval:
860       CaptureDefault = LCD_ByCopy;
861       break;
862
863     case CapturingScopeInfo::ImpCap_CapturedRegion:
864     case CapturingScopeInfo::ImpCap_LambdaByref:
865       CaptureDefault = LCD_ByRef;
866       break;
867
868     case CapturingScopeInfo::ImpCap_Block:
869       llvm_unreachable("block capture in lambda");
870       break;
871     }
872
873     // C++11 [expr.prim.lambda]p4:
874     //   If a lambda-expression does not include a
875     //   trailing-return-type, it is as if the trailing-return-type
876     //   denotes the following type:
877     // FIXME: Assumes current resolution to core issue 975.
878     if (LSI->HasImplicitReturnType) {
879       deduceClosureReturnType(*LSI);
880
881       //   - if there are no return statements in the
882       //     compound-statement, or all return statements return
883       //     either an expression of type void or no expression or
884       //     braced-init-list, the type void;
885       if (LSI->ReturnType.isNull()) {
886         LSI->ReturnType = Context.VoidTy;
887       }
888
889       // Create a function type with the inferred return type.
890       const FunctionProtoType *Proto
891         = CallOperator->getType()->getAs<FunctionProtoType>();
892       QualType FunctionTy
893         = Context.getFunctionType(LSI->ReturnType,
894                                   ArrayRef<QualType>(Proto->arg_type_begin(),
895                                                      Proto->getNumArgs()),
896                                   Proto->getExtProtoInfo());
897       CallOperator->setType(FunctionTy);
898     }
899
900     // C++ [expr.prim.lambda]p7:
901     //   The lambda-expression's compound-statement yields the
902     //   function-body (8.4) of the function call operator [...].
903     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
904     CallOperator->setLexicalDeclContext(Class);
905     Class->addDecl(CallOperator);
906     PopExpressionEvaluationContext();
907
908     // C++11 [expr.prim.lambda]p6:
909     //   The closure type for a lambda-expression with no lambda-capture
910     //   has a public non-virtual non-explicit const conversion function
911     //   to pointer to function having the same parameter and return
912     //   types as the closure type's function call operator.
913     if (Captures.empty() && CaptureDefault == LCD_None)
914       addFunctionPointerConversion(*this, IntroducerRange, Class,
915                                    CallOperator);
916
917     // Objective-C++:
918     //   The closure type for a lambda-expression has a public non-virtual
919     //   non-explicit const conversion function to a block pointer having the
920     //   same parameter and return types as the closure type's function call
921     //   operator.
922     if (getLangOpts().Blocks && getLangOpts().ObjC1)
923       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
924     
925     // Finalize the lambda class.
926     SmallVector<Decl*, 4> Fields;
927     for (RecordDecl::field_iterator i = Class->field_begin(),
928                                     e = Class->field_end(); i != e; ++i)
929       Fields.push_back(*i);
930     ActOnFields(0, Class->getLocation(), Class, Fields, 
931                 SourceLocation(), SourceLocation(), 0);
932     CheckCompletedCXXClass(Class);
933   }
934
935   if (LambdaExprNeedsCleanups)
936     ExprNeedsCleanups = true;
937   
938   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 
939                                           CaptureDefault, Captures, 
940                                           ExplicitParams, ExplicitResultType,
941                                           CaptureInits, ArrayIndexVars, 
942                                           ArrayIndexStarts, Body->getLocEnd(),
943                                           ContainsUnexpandedParameterPack);
944
945   // C++11 [expr.prim.lambda]p2:
946   //   A lambda-expression shall not appear in an unevaluated operand
947   //   (Clause 5).
948   if (!CurContext->isDependentContext()) {
949     switch (ExprEvalContexts.back().Context) {
950     case Unevaluated:
951     case UnevaluatedAbstract:
952       // We don't actually diagnose this case immediately, because we
953       // could be within a context where we might find out later that
954       // the expression is potentially evaluated (e.g., for typeid).
955       ExprEvalContexts.back().Lambdas.push_back(Lambda);
956       break;
957
958     case ConstantEvaluated:
959     case PotentiallyEvaluated:
960     case PotentiallyEvaluatedIfUsed:
961       break;
962     }
963   }
964   
965   return MaybeBindToTemporary(Lambda);
966 }
967
968 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
969                                                SourceLocation ConvLocation,
970                                                CXXConversionDecl *Conv,
971                                                Expr *Src) {
972   // Make sure that the lambda call operator is marked used.
973   CXXRecordDecl *Lambda = Conv->getParent();
974   CXXMethodDecl *CallOperator 
975     = cast<CXXMethodDecl>(
976         Lambda->lookup(
977           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
978   CallOperator->setReferenced();
979   CallOperator->setUsed();
980
981   ExprResult Init = PerformCopyInitialization(
982                       InitializedEntity::InitializeBlock(ConvLocation, 
983                                                          Src->getType(), 
984                                                          /*NRVO=*/false),
985                       CurrentLocation, Src);
986   if (!Init.isInvalid())
987     Init = ActOnFinishFullExpr(Init.take());
988   
989   if (Init.isInvalid())
990     return ExprError();
991   
992   // Create the new block to be returned.
993   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
994
995   // Set the type information.
996   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
997   Block->setIsVariadic(CallOperator->isVariadic());
998   Block->setBlockMissingReturnType(false);
999
1000   // Add parameters.
1001   SmallVector<ParmVarDecl *, 4> BlockParams;
1002   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1003     ParmVarDecl *From = CallOperator->getParamDecl(I);
1004     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1005                                               From->getLocStart(),
1006                                               From->getLocation(),
1007                                               From->getIdentifier(),
1008                                               From->getType(),
1009                                               From->getTypeSourceInfo(),
1010                                               From->getStorageClass(),
1011                                               /*DefaultArg=*/0));
1012   }
1013   Block->setParams(BlockParams);
1014
1015   Block->setIsConversionFromLambda(true);
1016
1017   // Add capture. The capture uses a fake variable, which doesn't correspond
1018   // to any actual memory location. However, the initializer copy-initializes
1019   // the lambda object.
1020   TypeSourceInfo *CapVarTSI =
1021       Context.getTrivialTypeSourceInfo(Src->getType());
1022   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1023                                     ConvLocation, 0,
1024                                     Src->getType(), CapVarTSI,
1025                                     SC_None);
1026   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1027                              /*Nested=*/false, /*Copy=*/Init.take());
1028   Block->setCaptures(Context, &Capture, &Capture + 1, 
1029                      /*CapturesCXXThis=*/false);
1030
1031   // Add a fake function body to the block. IR generation is responsible
1032   // for filling in the actual body, which cannot be expressed as an AST.
1033   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1034
1035   // Create the block literal expression.
1036   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1037   ExprCleanupObjects.push_back(Block);
1038   ExprNeedsCleanups = true;
1039
1040   return BuildBlock;
1041 }