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